[LeetCode] Maximum Trailing Zeros in a Cornered Path

2245. Maximum Trailing Zeros in a Cornered Path

You are given a 2D integer array grid of size m x n, where each cell contains a positive integer.

A cornered path is defined as a set of adjacent cells with at most one turn. More specifically, the path should exclusively move either horizontally or vertically up to the turn (if there is one), without returning to a previously visited cell. After the turn, the path will then move exclusively in the alternate direction: move vertically if it moved horizontally, and vice versa, also without returning to a previously visited cell.

The product of a path is defined as the product of all the values in the path.

Return the maximum number of trailing zeros in the product of a cornered path found in grid.

Note:

  • Horizontal movement means moving in either the left or right direction.
  • Vertical movement means moving in either the up or down direction.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
class Solution {
int countWith(int& n, int divisor) {
int res = 0;
while(!(n % divisor)) {
n /= divisor;
res++;
}
return res;
}
public:
int maxTrailingZeros(vector<vector<int>>& grid) {
int n = grid.size(), m = grid[0].size(), res = 0;
vector<vector<pair<int,int>>> rowPrefixSum(n, vector<pair<int,int>>(m, {0, 0})), colPrefixSum(n, vector<pair<int,int>>(m, {0, 0})), count(n, vector<pair<int,int>>(m, {0, 0}));

for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
int n = grid[i][j], ct = countWith(n, 2), cf = countWith(n, 5);

count[i][j] = {ct, cf};
if(j) rowPrefixSum[i][j] = rowPrefixSum[i][j - 1];
if(i) colPrefixSum[i][j] = colPrefixSum[i - 1][j];
rowPrefixSum[i][j].first += ct, rowPrefixSum[i][j].second += cf;
colPrefixSum[i][j].first += ct, colPrefixSum[i][j].second += cf;
}
}

for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
auto [upt, upf] = colPrefixSum[i][j];
auto lot = colPrefixSum[n - 1][j].first - (i ? colPrefixSum[i - 1][j].first : 0), lof = colPrefixSum[n - 1][j].second - (i ? colPrefixSum[i - 1][j].second : 0);
auto [let, lef] = rowPrefixSum[i][j];
auto rit = rowPrefixSum[i][m - 1].first - (j ? rowPrefixSum[i][j - 1].first : 0), rif = rowPrefixSum[i][m - 1].second - (j ? rowPrefixSum[i][j - 1].second : 0);

res = max({res,
min(upt + let - count[i][j].first, upf + lef - count[i][j].second),
min(upt + rit - count[i][j].first, upf + rif - count[i][j].second),
min(lot + let - count[i][j].first, lof + lef - count[i][j].second),
min(lot + rit - count[i][j].first, lof + rif - count[i][j].second)
});
}
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/04/17/PS/LeetCode/maximum-trailing-zeros-in-a-cornered-path/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.