- 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
- 55 lines of C++ from the credited upstream file 3086.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 long long minimumMoves(vector<int>& nums, int k, int maxChanges) {4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 constexpr int kNumOfIndicesWithinOneDistance = 3;27 long ans = LONG_MAX;28 vector<int> oneIndices; 29 vector<long> prefix{0}; 30 31 for (int i = 0; i < nums.size(); ++i)32 if (nums[i] == 1)33 oneIndices.push_back(i);34 35 for (const int oneIndex : oneIndices)36 prefix.push_back(prefix.back() + oneIndex);37 38 const int minOnesByTwo = max(0, k - maxChanges);39 const int maxOnesByTwo =40 min({k, minOnesByTwo + kNumOfIndicesWithinOneDistance,41 static_cast<int>(oneIndices.size())});42 43 for (int onesByTwo = minOnesByTwo; onesByTwo <= maxOnesByTwo; ++onesByTwo)44 for (int l = 0; l + onesByTwo < prefix.size(); ++l) {45 const int r = l + onesByTwo; 46 const long cost1 = (k - onesByTwo) * 2;47 const long cost2 = (prefix[r] - prefix[(l + r) / 2]) -48 (prefix[(l + r + 1) / 2] - prefix[l]);49 ans = min(ans, cost1 + cost2);50 }51 52 return ans;53 }54};55