- Translate each rule into one explicit state update.
- Maintain the invariant after every processed item.
- Return the accumulated state once all relevant input has been handled.
Code notes
- 89 lines of C++ from the credited upstream file largest-local-values-in-a-matrix-ii.cpp.
- The implementation visibly relies on sequence storage.
- 11 loop blocks detected.
Complexity
Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.
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 int countLocalMaximums(vector<vector<int>>& matrix) {8 const int n = size(matrix);9 const int m = size(matrix[0]);10 SparseTable2D st(matrix, [](const auto& x, const auto& y) {11 return x < y ? y : x;12 });13 14 int result = 0;15 for (int r = 0; r < n; ++r) {16 const auto& row = matrix[r];17 for (int c = 0; c < m; ++c) {18 const auto& x = row[c];19 if (x == 0) {20 continue;21 }22 const auto& r1 = max(r - x, 0);23 const auto& r2 = min(r + x, n - 1);24 const auto& c1 = max(c - x, 0);25 const auto& c2 = min(c + x, m - 1);26 const auto& tl = r - x >= 0 && c - x >= 0;27 const auto& tr = r - x >= 0 && c + x <= m - 1;28 const auto& bl = r + x <= n - 1 && c - x >= 0;29 const auto& br = r + x <= n - 1 && c + x <= m - 1;30 const auto& topX = tl || tr, botX = bl || br;31 if (max(st.query(r1, c1 + (tl || bl ? 1 : 0), r2, c2 - (tr || br ? 1 : 0)),32 st.query(r1 + (tl || tr ? 1 : 0), c1, r2 - (bl || br ? 1 : 0), c2)) <= x) {33 ++result;34 }35 }36 }37 return result;38 }39 40private:41 42 class SparseTable2D {43 public:44 45 SparseTable2D(const vector<vector<int>>& matrix, function<int(int, int)> fn)46 : fn(fn) {47 const auto& n = size(matrix);48 const auto& m = size(matrix[0]);49 const auto& logn = __lg(n);50 const auto& logm = __lg(m);51 st.assign(logn + 1, vector<vector<vector<int>>>(logm + 1, vector<vector<int>>(n, vector<int>(m)))); 52 for (int r = 0; r < n; ++r) {53 for (int c = 0; c < m; ++c) {54 st[0][0][r][c] = matrix[r][c];55 }56 }57 for (int j = 1; j <= logm; ++j) {58 for (int r = 0; r < n; ++r) {59 for (int c = 0; c + (1 << j) <= m; ++c) {60 st[0][j][r][c] = fn(st[0][j - 1][r][c], st[0][j - 1][r][c + (1 << (j - 1))]);61 }62 }63 } 64 for (int i = 1; i <= logn; ++i) {65 for (int j = 0; j <= logm; ++j) {66 for (int r = 0; r + (1 << i) <= n; ++r) {67 for (int c = 0; c + (1 << j) <= m; ++c) {68 st[i][j][r][c] = fn(st[i - 1][j][r][c], st[i - 1][j][r + (1 << (i - 1))][c]);69 }70 }71 }72 }73 }74 75 int query(int r1, int c1, int r2, int c2) const {76 const int i = __lg(r2 - r1 + 1);77 const int j = __lg(c2 - c1 + 1);78 return fn(79 fn(st[i][j][r1][c1], st[i][j][r1][c2 - (1 << j) + 1]),80 fn(st[i][j][r2 - (1 << i) + 1][c1], st[i][j][r2 - (1 << i) + 1][c2 - (1 << j) + 1])81 );82 }83 84 private:85 vector<vector<vector<vector<int>>>> st;86 const function<int(int, int)> fn;87 };88};89