- 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
- 40 lines of C++ from the credited upstream file 3445.cpp.
- 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:3 int maxDifference(string s, int k) {4 int ans = INT_MIN;5 6 for (const auto& [a, b] : getPermutations()) {7 8 9 vector<vector<int>> minDiff(2, vector<int>(2, INT_MAX / 2));10 vector<int> prefixA{0}; 11 vector<int> prefixB{0}; 12 for (int l = 0, r = 0; r < s.length(); ++r) {13 prefixA.push_back(prefixA.back() + (s[r] == a ? 1 : 0));14 prefixB.push_back(prefixB.back() + (s[r] == b ? 1 : 0));15 while (r - l + 1 >= k && 16 prefixA[l] < prefixA.back() && 17 prefixB[l] < prefixB.back()) { 18 minDiff[prefixA[l] % 2][prefixB[l] % 2] = min(19 minDiff[prefixA[l] % 2][prefixB[l] % 2], prefixA[l] - prefixB[l]);20 ++l;21 }22 ans = max(ans, (prefixA.back() - prefixB.back()) -23 minDiff[1 - prefixA.back() % 2][prefixB.back() % 2]);24 }25 }26 27 return ans;28 }29 30 private:31 vector<pair<char, char>> getPermutations() {32 vector<pair<char, char>> permutations;33 for (const char a : "01234")34 for (const char b : "01234")35 if (a != b)36 permutations.emplace_back(a, b);37 return permutations;38 }39};40