- 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
- 37 lines of Java from the credited upstream file 2838.java.
- 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 long[] maximumCoins(int[] heroes, int[] monsters, int[] coins) {3 Pair<Integer, Integer>[] monsterAndCoins = getSortedMonsterAndCoins(monsters, coins);4 long[] ans = new long[heroes.length];5 long[] coinsPrefix = new long[coins.length + 1];6 7 for (int i = 0; i < monsterAndCoins.length; ++i)8 coinsPrefix[i + 1] = coinsPrefix[i] + monsterAndCoins[i].getValue();9 10 for (int i = 0; i < heroes.length; ++i)11 ans[i] = coinsPrefix[firstGreaterEqual(monsterAndCoins, heroes[i])];12 13 return ans;14 }15 16 private Pair<Integer, Integer>[] getSortedMonsterAndCoins(int[] monsters, int[] coins) {17 Pair<Integer, Integer>[] monsterAndCoins = new Pair[monsters.length];18 for (int i = 0; i < monsters.length; ++i)19 monsterAndCoins[i] = new Pair<>(monsters[i], coins[i]);20 Arrays.sort(monsterAndCoins, Comparator.comparingInt(Pair::getKey));21 return monsterAndCoins;22 }23 24 private int firstGreaterEqual(Pair<Integer, Integer>[] monsterAndCoins, int hero) {25 int l = 0;26 int r = monsterAndCoins.length;27 while (l < r) {28 final int m = (l + r) / 2;29 if (monsterAndCoins[m].getKey() > hero)30 r = m;31 else32 l = m + 1;33 }34 return l;35 }36}37