Approach
Sorting and greedy selection
For Maximum Coins From K Consecutive Bags, the implementation first exposes a useful order, then scans that order while making locally justified choices.
- Choose the key that reveals the greedy or grouping structure.
- Sort the relevant records by that key.
- Scan in order, maintaining the invariant that makes each local choice safe.
Code notes
- 58 lines of C++ from the credited upstream file 3413.cpp.
- The implementation visibly relies on sequence storage.
- 3 loop blocks detected.
Complexity
Sorting is typically the dominant term unless the subsequent scan uses a more expensive nested operation.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public:3 long long maximumCoins(vector<vector<int>>& coins, int k) {4 vector<vector<int>> negatedCoins = negateLeftRight(coins);5 return max(slide(coins, k), slide(negatedCoins, k));6 }7 8 private:9 vector<vector<int>> negateLeftRight(const vector<vector<int>> coins) {10 vector<vector<int>> res;11 for (const vector<int>& coin : coins) {12 const int l = coin[0];13 const int r = coin[1];14 const int c = coin[2];15 res.push_back({-r, -l, c});16 }17 return res;18 }19 20 long slide(vector<vector<int>>& coins, int k) {21 long res = 0;22 long windowSum = 0;23 int j = 0;24 25 ranges::sort(coins);26 27 for (const vector<int>& coin : coins) {28 const int li = coin[0];29 const int ri = coin[1];30 const int ci = coin[2];31 const int rightBoundary = li + k;32 33 34 while (j + 1 < coins.size() && coins[j + 1][0] < rightBoundary) {35 const int lj = coins[j][0];36 const int rj = coins[j][1];37 const int cj = coins[j][2];38 windowSum += static_cast<long>(rj - lj + 1) * cj;39 ++j;40 }41 42 43 long last = 0;44 if (j < coins.size() && coins[j][0] < rightBoundary) {45 const int lj = coins[j][0];46 const int rj = coins[j][1];47 const int cj = coins[j][2];48 last = static_cast<long>(min(rightBoundary - 1, rj) - lj + 1) * cj;49 }50 51 res = max(res, windowSum + last);52 windowSum -= static_cast<long>(ri - li + 1) * ci;53 }54 55 return res;56 }57};58