- 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 C++ from the credited upstream file 2106.cpp.
- The implementation visibly relies on sequence storage.
- 3 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 int maxTotalFruits(vector<vector<int>>& fruits, int startPos, int k) {4 const int maxRight = max(startPos, fruits.back()[0]);5 int ans = 0;6 vector<int> amounts(1 + maxRight);7 vector<int> prefix(2 + maxRight);8 9 for (const vector<int>& f : fruits)10 amounts[f[0]] = f[1];11 12 partial_sum(amounts.begin(), amounts.end(), prefix.begin() + 1);13 14 auto getFruits = [&](int leftSteps, int rightSteps) {15 const int l = max(0, startPos - leftSteps);16 const int r = min(maxRight, startPos + rightSteps);17 return prefix[r + 1] - prefix[l];18 };19 20 21 const int maxRightSteps = min(maxRight - startPos, k);22 for (int rightSteps = 0; rightSteps <= maxRightSteps; ++rightSteps) {23 const int leftSteps = max(0, k - 2 * rightSteps); 24 ans = max(ans, getFruits(leftSteps, rightSteps));25 }26 27 28 const int maxLeftSteps = min(startPos, k);29 for (int leftSteps = 0; leftSteps <= maxLeftSteps; ++leftSteps) {30 const int rightSteps = max(0, k - 2 * leftSteps); 31 ans = max(ans, getFruits(leftSteps, rightSteps));32 }33 34 return ans;35 }36};37