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