-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
maximum-trailing-zeros-in-a-cornered-path.cpp
53 lines (51 loc) · 1.92 KB
/
maximum-trailing-zeros-in-a-cornered-path.cpp
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
45
46
47
48
49
50
51
52
53
// Time: O(m * n)
// Space: O(m * n)
// prefix sum
class Solution {
public:
int maxTrailingZeros(vector<vector<int>>& grid) {
const auto& factor = [](int x) {
static const array<int, 2> primes = {2, 5};
array<int, 2> cnt = {0, 0};
for (int i = 0; i < size(primes); ++i) {
while (x && x % primes[i] == 0) {
x /= primes[i];
++cnt[i];
}
}
return cnt;
};
const auto& add = [](const auto& a, const auto& b) {
return array<int, 2>{a[0] + b[0], a[1] + b[1]};
};
const auto& sub = [](const auto& a, const auto& b) {
return array<int, 2>{a[0] - b[0], a[1] - b[1]};
};
const auto& count = [](const auto& a) {
return min(a[0], a[1]);
};
vector<vector<array<int, 2>>> left(size(grid), vector<array<int, 2>>(size(grid[0])));
for (int i = 0; i < size(grid); ++i) {
left[i][0] = factor(grid[i][0]);
for (int j = 1; j < size(grid[0]); ++j) {
left[i][j] = add(left[i][j - 1], factor(grid[i][j]));
}
}
int result = 0;
for (int j = 0; j < size(grid[0]); ++j) {
array<int, 2> total = {0, 0};
for (int i = 0; i < size(grid); ++i) {
total = add(total, factor(grid[i][j]));
}
array<int, 2> up = {0, 0};
for (int i = 0; i < size(grid); ++i) {
const auto& right = j ? sub(left[i].back(), left[i][j - 1]) : left[i].back();
result = max({result, count(add(left[i][j], up)), count(add(right, up))});
up = add(up, factor(grid[i][j]));
const auto& down = sub(total, up);
result = max({result, count(add(left[i][j], down)), count(add(right, down))});
}
}
return result;
}
};