- 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
- 60 lines of C++ from the credited upstream file minimum-operations-to-make-all-grid-elements-equal.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.
123 45class Solution {6public:7 long long minOperations(vector<vector<int>>& grid, int k) {8 int64_t c = 0, target = 0, mn = numeric_limits<int64_t>::min();9 bool found = false;10 vector<vector<int64_t>> lookup(k, vector<int64_t>(size(grid[0])));11 vector<int64_t> cnt(size(grid[0]));12 for (int i = 0; i < size(grid); ++i) {13 int64_t total = 0;14 for (int j = 0; j < size(grid[0]); ++j) {15 total += cnt[j];16 const auto& diff = -(grid[i][j] + total); 17 if (i + k - 1 < size(grid) && j + k - 1 < size(grid[0])) {18 lookup[i % k][j] = diff;19 cnt[j] += diff;20 total += diff;21 c += diff;22 if (i % k == 0 && j % k == 0) { 23 mn = max(mn, -diff);24 } else if (diff < 0) { 25 return -1;26 }27 } else {28 if ((i / k + 1) * k <= size(grid) && (j / k + 1) * k <= size(grid[0])) {29 if (diff) {30 return -1;31 }32 } else {33 if (!found) {34 found = true;35 target = -diff;36 } else if (target != -diff) {37 return -1;38 }39 }40 }41 if (j - k + 1 >= 0) {42 total -= cnt[j - k + 1];43 }44 }45 if (i - k + 1 >= 0) {46 for (int j = 0; j < size(grid[0]); ++j) {47 cnt[j] -= lookup[(i - k + 1) % k][j];48 lookup[(i - k + 1) % k][j] = 0;49 }50 }51 }52 if (!found) {53 target = mn;54 } else if (target < mn) {55 return -1;56 }57 return c + target * ((size(grid) / k) * (size(grid[0]) / k));58 }59};60