- Choose the invariant that makes a window valid or useful.
- Advance the right boundary and add the new element.
- Move the left boundary only as needed while maintaining the invariant and updating the answer.
Code notes
- 43 lines of C++ from the credited upstream file 2838.cpp.
- The implementation visibly relies on sequence storage.
- 4 loop blocks detected.
Complexity
Confirm that neither pointer moves backwards; if so, the scan is usually linear apart from the window’s data-structure operations.
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 vector<long long> maximumCoins(vector<int>& heroes, vector<int>& monsters,4 vector<int>& coins) {5 const vector<pair<int, int>> monsterAndCoins =6 getSortedMonsterAndCoins(monsters, coins);7 vector<long long> ans;8 vector<long long> coinsPrefix{0};9 10 for (const auto& [_, coin] : monsterAndCoins)11 coinsPrefix.push_back(coinsPrefix.back() + coin);12 13 for (const int hero : heroes)14 ans.push_back(coinsPrefix[firstGreaterEqual(monsterAndCoins, hero)]);15 16 return ans;17 }18 19 private:20 vector<pair<int, int>> getSortedMonsterAndCoins(const vector<int>& monsters,21 const vector<int>& coins) {22 vector<pair<int, int>> monsterAndCoins;23 for (int i = 0; i < monsters.size(); ++i)24 monsterAndCoins.emplace_back(monsters[i], coins[i]);25 ranges::sort(monsterAndCoins);26 return monsterAndCoins;27 }28 29 int firstGreaterEqual(const vector<pair<int, int>>& monsterAndCoins,30 int hero) {31 int l = 0;32 int r = monsterAndCoins.size();33 while (l < r) {34 const int m = (l + r) / 2;35 if (monsterAndCoins[m].first > hero)36 r = m;37 else38 l = m + 1;39 }40 return l;41 }42};43