- 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
- 67 lines of C++ from the credited upstream file 2245.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 maxTrailingZeros(vector<vector<int>>& grid) {4 const int m = grid.size();5 const int n = grid[0].size();6 7 8 9 10 vector<vector<int>> leftPrefix2(m, vector<int>(n));11 vector<vector<int>> leftPrefix5(m, vector<int>(n));12 vector<vector<int>> topPrefix2(m, vector<int>(n));13 vector<vector<int>> topPrefix5(m, vector<int>(n));14 15 for (int i = 0; i < m; ++i)16 for (int j = 0; j < n; ++j) {17 leftPrefix2[i][j] = getCount(grid[i][j], 2);18 leftPrefix5[i][j] = getCount(grid[i][j], 5);19 if (j > 0) {20 leftPrefix2[i][j] += leftPrefix2[i][j - 1];21 leftPrefix5[i][j] += leftPrefix5[i][j - 1];22 }23 }24 25 for (int j = 0; j < n; ++j)26 for (int i = 0; i < m; ++i) {27 topPrefix2[i][j] = getCount(grid[i][j], 2);28 topPrefix5[i][j] = getCount(grid[i][j], 5);29 if (i > 0) {30 topPrefix2[i][j] += topPrefix2[i - 1][j];31 topPrefix5[i][j] += topPrefix5[i - 1][j];32 }33 }34 35 int ans = 0;36 for (int i = 0; i < m; ++i)37 for (int j = 0; j < n; ++j) {38 const int curr2 = getCount(grid[i][j], 2);39 const int curr5 = getCount(grid[i][j], 5);40 const int l2 = leftPrefix2[i][j];41 const int l5 = leftPrefix5[i][j];42 const int r2 = leftPrefix2[i][n - 1] - (j ? leftPrefix2[i][j - 1] : 0);43 const int r5 = leftPrefix5[i][n - 1] - (j ? leftPrefix5[i][j - 1] : 0);44 const int t2 = topPrefix2[i][j];45 const int t5 = topPrefix5[i][j];46 const int d2 = topPrefix2[m - 1][j] - (i ? topPrefix2[i - 1][j] : 0);47 const int d5 = topPrefix5[m - 1][j] - (i ? topPrefix5[i - 1][j] : 0);48 ans = max({ans, min(l2 + t2 - curr2, l5 + t5 - curr5),49 min(r2 + t2 - curr2, r5 + t5 - curr5),50 min(l2 + d2 - curr2, l5 + d5 - curr5),51 min(r2 + d2 - curr2, r5 + d5 - curr5)});52 }53 54 return ans;55 }56 57 private:58 int getCount(int num, int factor) {59 int count = 0;60 while (num % factor == 0) {61 num /= factor;62 ++count;63 }64 return count;65 }66};67