Java | Prefix sums of 10, 5, 2
Yes, you can do away with 5 and 2 only.\n```\nclass Solution {\n    static int R= 0, L= 1, D= 2, U= 3; // grid iteration direction index\n    static int Z= 0, F
Yes, you can do away with 5 and 2 only.\n```\nclass Solution {\n    static int R= 0, L= 1, D= 2, U= 3; // grid iteration direction index\n    static int Z= 0, F= 1, E= 2;       // count of zeros, fives and even numbers\n    static int[] EMPTY= {0, 0, 0};     // empty array of factor counts [Z, F, E]\n    \n    public int maxTrailingZeros(int[][] grid) {\n        int m= grid.length, n= grid[0].length;\n        \n        // calculate 10,5,2 factors for each number in the grid\n        int[][][] fs= new int[m][n][3];\n        for(int i=0; i<m; i++)\n            for(int j=0; j<n; j++)\n                fact(fs[i][j], grid[i][j]);\n        \n        // calculate ps matrices of factors in all directions\n        int[][][][] ps= new int[m][n][4][3];       \n        for(int i=0; i<m; i++){\n            for(int j=0; j<n; j++)\n                add(ps[i][j][R], fs[i][j], j==0 ? EMPTY : ps[i][j-1][R]);\n            for(int j=n-1; j>-1; j--)\n                add(ps[i][j][L], fs[i][j], j==n-1 ? EMPTY : ps[i][j+1][L]);\n        }\n        for(int j=0; j<n; j++){\n            for(int i=0; i<m; i++)\n                add(ps[i][j][D], fs[i][j], i==0 ? EMPTY : ps[i-1][j][D]);\n            for(int i=m-1; i>-1; i--)\n                add(ps[i][j][U], fs[i][j], i==m-1 ? EMPTY : ps[i+1][j][U]);     \n        }\n\n        // use ps matrices to calculate answer \n        int ans= 0;\n        for(int i=0; i<m; i++){\n            for(int j=0; j<n; j++){\n                ans= Math.max(ans, calc(ps[i][j][L], i==m-1 ? EMPTY : ps[i+1][j][U]));\n                ans= Math.max(ans, calc(ps[i][j][L], i==0 ? EMPTY : ps[i-1][j][D]));\n                ans= Math.max(ans, calc(ps[i][j][R], i==m-1 ? EMPTY : ps[i+1][j][U]));\n                ans= Math.max(ans, calc(ps[i][j][R], i==0 ? EMPTY : ps[i-1][j][D]));\n            }\n        }\n        return ans;\n    }\n\n    void fact(int[] fs, int val){\n        while(val!=0 && val%10==0){fs[Z]++; val/=10;}\n        while(val!=0 && val%5==0){fs[F]++; val/=5;} \n        while(val!=0 && val%2==0){fs[E]++; val/=2;}\n    }\n    \n    void add(int[] ans, int[] a, int[] b){\n        for(int i=0; i<3; i++) ans[i]= a[i]+b[i];\n    }\n    \n    int calc(int[] a, int[] b){\n        return a[Z]+b[Z] + Math.min(a[F]+b[F], a[E]+b[E]);\n    }\n}
[]