- 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 2106.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 int maxTotalFruits(int[][] fruits, int startPos, int k) {3 final int maxRight = Math.max(startPos, fruits[fruits.length - 1][0]);4 int ans = 0;5 int[] amounts = new int[1 + maxRight];6 int[] prefix = new int[2 + maxRight];7 8 for (int[] f : fruits)9 amounts[f[0]] = f[1];10 11 for (int i = 0; i + 1 < prefix.length; ++i)12 prefix[i + 1] = prefix[i] + amounts[i];13 14 15 final int maxRightSteps = Math.min(maxRight - startPos, k);16 for (int rightSteps = 0; rightSteps <= maxRightSteps; ++rightSteps) {17 final int leftSteps = Math.max(0, k - 2 * rightSteps); 18 ans = Math.max(ans, getFruits(startPos, maxRight, leftSteps, rightSteps, prefix));19 }20 21 22 final int maxLeftSteps = Math.min(startPos, k);23 for (int leftSteps = 0; leftSteps <= maxLeftSteps; ++leftSteps) {24 final int rightSteps = Math.max(0, k - 2 * leftSteps); 25 ans = Math.max(ans, getFruits(startPos, maxRight, leftSteps, rightSteps, prefix));26 }27 28 return ans;29 }30 31 private int getFruits(int startPos, int maxRight, int leftSteps, int rightSteps, int[] prefix) {32 final int l = Math.max(0, startPos - leftSteps);33 final int r = Math.min(maxRight, startPos + rightSteps);34 return prefix[r + 1] - prefix[l];35 }36}37