- 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
- 63 lines of C++ from the credited upstream file 1895.cpp.
- The implementation visibly relies on sequence storage.
- 7 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.
1class Solution {2 public:3 int largestMagicSquare(vector<vector<int>>& grid) {4 const int m = grid.size();5 const int n = grid[0].size();6 7 vector<vector<int>> prefixRow(m, vector<int>(n + 1));8 9 vector<vector<int>> prefixCol(n, vector<int>(m + 1));10 11 for (int i = 0; i < m; ++i)12 for (int j = 0; j < n; ++j) {13 prefixRow[i][j + 1] = prefixRow[i][j] + grid[i][j];14 prefixCol[j][i + 1] = prefixCol[j][i] + grid[i][j];15 }16 17 for (int k = min(m, n); k >= 2; --k)18 if (containsMagicSquare(grid, prefixRow, prefixCol, k))19 return k;20 21 return 1;22 }23 24 private:25 26 bool containsMagicSquare(const vector<vector<int>>& grid,27 const vector<vector<int>>& prefixRow,28 const vector<vector<int>>& prefixCol, int k) {29 for (int i = 0; i + k - 1 < grid.size(); ++i)30 for (int j = 0; j + k - 1 < grid[0].size(); ++j)31 if (isMagicSquare(grid, prefixRow, prefixCol, i, j, k))32 return true;33 return false;34 }35 36 37 bool isMagicSquare(const vector<vector<int>>& grid,38 const vector<vector<int>>& prefixRow,39 const vector<vector<int>>& prefixCol, int i, int j,40 int k) {41 int diag = 0;42 int antiDiag = 0;43 for (int d = 0; d < k; ++d) {44 diag += grid[i + d][j + d];45 antiDiag += grid[i + d][j + k - 1 - d];46 }47 if (diag != antiDiag)48 return false;49 for (int d = 0; d < k; ++d) {50 if (getSum(prefixRow, i + d, j, j + k - 1) != diag)51 return false;52 if (getSum(prefixCol, j + d, i, i + k - 1) != diag)53 return false;54 }55 return true;56 }57 58 59 int getSum(const vector<vector<int>>& prefix, int i, int l, int r) {60 return prefix[i][r + 1] - prefix[i][l];61 }62};63