Maximum Trailing Zeros in a Cornered Path LeetCode solution in JavaScript

1
var maxTrailingZeros = function (grid) {
2
const m = grid.length;
3
const n = grid[0].length;
4

5
const postfixCols = [];
6

7
for (let i = 0; i < m; ++i) {
8
for (let j = 0; j < n; ++j) {
9
const num = grid[i][j];
10

11
if (postfixCols[j] == null) postfixCols[j] = { 2: 0, 5: 0 };
12

13
postfixCols[j]["2"] += getCount(num, 2);
14
postfixCols[j]["5"] += getCount(num, 5);
15
}
16
}
17

18
const prefixCols = [];
19

20
for (let j = 0; j < n; ++j) {
21
prefixCols[j] = { 0: 0, 2: 0, 5: 0 };
22
}
23

24
let maxZeros = 0;
25

26
for (let i = 0; i < m; ++i) {
27
const postfixRow = { 0: 0, 2: 0, 5: 0 };
28

29
for (let j = n - 1; j >= 0; --j) {
30
const num = grid[i][j];
31

32
postfixRow["2"] += getCount(num, 2);
33
postfixRow["5"] += getCount(num, 5);
34
}
35

36
let prefixRow = { 0: 0, 2: 0, 5: 0 };
37

38
for (let j = 0; j < n; ++j) {
39
const num = grid[i][j];
40

41
const twoCount = getCount(num, 2);
42
const fiveCount = getCount(num, 5);
43

44
postfixRow["2"] -= twoCount;
45
postfixCols[j]["2"] -= twoCount;
46

47
postfixRow["5"] -= fiveCount;
48
postfixCols[j]["5"] -= fiveCount;
49

50
// down-right => prefixCol + postfixRow
51
const downRight = calculateTrailingZeros(prefixCols[j], postfixRow, num);
52
// down-left => prefixCol + prefixRow
53
const downLeft = calculateTrailingZeros(prefixCols[j], prefixRow, num);
54
// up-right => postfixCols + postfixRow
55
const upRight = calculateTrailingZeros(postfixCols[j], postfixRow, num);
56
// up-left => postfixCols + prefixRow
57
const upLeft = calculateTrailingZeros(postfixCols[j], prefixRow, num);
58

59
maxZeros = Math.max(maxZeros, downRight, downLeft, upRight, upLeft);
60

61
prefixRow["2"] += twoCount;
62
prefixCols[j]["2"] += twoCount;
63

64
prefixRow["5"] += fiveCount;
65
prefixCols[j]["5"] += fiveCount;
66
}
67
}
68

69
return maxZeros;
70

71
function calculateTrailingZeros(col, row, currNum) {
72
let twosCount = 0;
73
let fivesCount = 0;
74
let zerosCount = 0;
75

76
twosCount = row["2"] + col["2"];
77
fivesCount = row["5"] + col["5"];
78

79
twosCount += getCount(currNum, 2);
80
fivesCount += getCount(currNum, 5);
81
return Math.min(twosCount, fivesCount);
82
}
83

84
function getCount(num, divisor) {
85
let count = 0;
86

87
while (num % divisor === 0) {
88
++count;
89
num /= divisor;
90
}
91

92
return count;
93
}
94
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0