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