- 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
- 82 lines of C++ from the credited upstream file minimum-absolute-difference-in-sliding-submatrix.cpp.
- The implementation visibly relies on sequence storage.
- 12 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 vector<vector<int>> minAbsDiff(vector<vector<int>>& grid, int k) {8 vector<vector<int>> result(size(grid) - k + 1, vector<int>(size(grid[0]) - k + 1, -1));9 multiset<int> bst;10 for (int di = 0; di < k; ++di) {11 for (int dj = 0; dj < k; ++dj) {12 bst.emplace(grid[0 + di][0 + dj]);13 }14 }15 for (int i = 0; i + (k - 1) < size(grid); ++i) {16 multiset<int> bst2(bst);17 for (int j = 0; j + (k - 1) < size(grid[0]); ++j) {18 int mn = numeric_limits<int>::max();19 int prev = numeric_limits<int>::min();20 for (const auto& x : bst2) {21 if (prev != numeric_limits<int>::min() && x != prev) {22 mn = min(mn, x - prev);23 }24 prev = x;25 }26 result[i][j] = mn != numeric_limits<int>::max() ? mn : 0;27 if (j + 1 == size(grid[0]) - (k - 1)) {28 continue;29 }30 for (int di = 0; di < k; ++di) {31 bst2.erase(bst2.find(grid[i + di][j]));32 bst2.emplace(grid[i + di][j + k]);33 }34 }35 if (i + 1 == size(grid) - (k-1)) {36 continue;37 }38 for (int dj = 0; dj < k; ++dj) {39 bst.erase(bst.find(grid[i][0 + dj]));40 bst.emplace(grid[i + k][0 + dj]);41 }42 }43 return result;44 }45};46 47484950class Solution2 {51public:52 vector<vector<int>> minAbsDiff(vector<vector<int>>& grid, int k) {53 vector<vector<int>> result(size(grid) - k + 1, vector<int>(size(grid[0]) - k + 1, -1));54 for (int i = 0; i + (k - 1) < size(grid); ++i) {55 for (int j = 0; j + (k - 1) < size(grid[0]); ++j) {56 vector<int> vals;57 for (int di = 0; di < k; ++di) {58 for (int dj = 0; dj < k; ++dj) {59 vals.emplace_back(grid[i + di][j + dj]);60 }61 }62 sort(begin(vals), end(vals));63 vals.erase(unique(begin(vals), end(vals)), end(vals));64 if (size(vals) == 1) {65 result[i][j] = 0;66 continue;67 }68 int mn = numeric_limits<int>::max();69 int prev = numeric_limits<int>::min();70 for (const auto& x : vals) {71 if (prev != numeric_limits<int>::min()) {72 mn = min(mn, x - prev);73 }74 prev = x;75 }76 result[i][j] = mn;77 }78 }79 return result;80 }81};82