- 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
- 45 lines of Java from the credited upstream file 3445.java.
- The implementation visibly relies on sequence storage.
- 5 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 maxDifference(String s, int k) {3 int ans = Integer.MIN_VALUE;4 5 for (Pair<Character, Character> pair : getPermutations()) {6 final char a = pair.getKey();7 final char b = pair.getValue();8 9 10 11 int[][] minDiff = new int[2][2];12 Arrays.stream(minDiff).forEach(A -> Arrays.fill(A, Integer.MAX_VALUE / 2));13 14 List<Integer> prefixA = new ArrayList<>(List.of(0));15 16 List<Integer> prefixB = new ArrayList<>(List.of(0));17 for (int l = 0, r = 0; r < s.length(); ++r) {18 prefixA.add(prefixA.get(prefixA.size() - 1) + (s.charAt(r) == a ? 1 : 0));19 prefixB.add(prefixB.get(prefixB.size() - 1) + (s.charAt(r) == b ? 1 : 0));20 while (r - l + 1 >= k && 21 prefixA.get(l) < prefixA.get(prefixA.size() - 1) && 22 prefixB.get(l) < prefixB.get(prefixB.size() - 1)) { 23 minDiff[prefixA.get(l) % 2][prefixB.get(l) % 2] = Math.min(24 minDiff[prefixA.get(l) % 2][prefixB.get(l) % 2], prefixA.get(l) - prefixB.get(l));25 ++l;26 }27 ans = Math.max(ans, (prefixA.get(prefixA.size() - 1) - prefixB.get(prefixB.size() - 1)) -28 minDiff[1 - prefixA.get(prefixA.size() - 1) % 2]29 [prefixB.get(prefixB.size() - 1) % 2]);30 }31 }32 33 return ans;34 }35 36 private List<Pair<Character, Character>> getPermutations() {37 List<Pair<Character, Character>> permutations = new ArrayList<>();38 for (final char a : "01234".toCharArray())39 for (final char b : "01234".toCharArray())40 if (a != b)41 permutations.add(new Pair<>(a, b));42 return permutations;43 }44}45