- Identify the ordered answer range or sorted search domain.
- Write a predicate whose truth changes only once.
- Move the appropriate boundary after each midpoint check and return the final feasible position.
Code notes
- 58 lines of Java from the credited upstream file 3413.java.
- The implementation visibly relies on sequence storage.
- 3 loop blocks detected.
Complexity
Multiply the logarithmic number of midpoint checks by the cost of one predicate evaluation.
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[][] coins, int k) {3 int[][] negatedCoins = negateLeftRight(coins);4 return Math.max(slide(coins, k), slide(negatedCoins, k));5 }6 7 private int[][] negateLeftRight(int[][] coins) {8 int[][] res = new int[coins.length][3];9 for (int i = 0; i < coins.length; ++i) {10 final int l = coins[i][0];11 final int r = coins[i][1];12 final int c = coins[i][2];13 res[i][0] = -r;14 res[i][1] = -l;15 res[i][2] = c;16 }17 return res;18 }19 20 private long slide(int[][] coins, int k) {21 long res = 0;22 long windowSum = 0;23 int j = 0;24 25 Arrays.sort(coins, Comparator.comparingInt((int[] coin) -> coin[0]));26 27 for (int[] coin : coins) {28 final int li = coin[0];29 final int ri = coin[1];30 final int ci = coin[2];31 final int rightBoundary = li + k;32 33 34 while (j + 1 < coins.length && coins[j + 1][0] < rightBoundary) {35 final int lj = coins[j][0];36 final int rj = coins[j][1];37 final int cj = coins[j][2];38 windowSum += (long) (rj - lj + 1) * cj;39 ++j;40 }41 42 43 long last = 0;44 if (j < coins.length && coins[j][0] < rightBoundary) {45 final int lj = coins[j][0];46 final int rj = coins[j][1];47 final int cj = coins[j][2];48 last = (long) (Math.min(rightBoundary - 1, rj) - lj + 1) * cj;49 }50 51 res = Math.max(res, windowSum + last);52 windowSum -= (long) (ri - li + 1) * ci;53 }54 55 return res;56 }57}58