Skip to content

Commit 95549d1

Browse files
authored
Create 1594-maximum-non-negative-product-in-a-matrix.js
1 parent ad3a650 commit 95549d1

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
/**
2+
* @param {number[][]} grid
3+
* @return {number}
4+
*/
5+
const maxProductPath = function (grid) {
6+
const m = grid.length,
7+
n = grid[0].length,
8+
MOD = 1e9 + 7;
9+
const mx = Array.from({ length: m }, () => Array(n).fill(0));
10+
const mn = Array.from({ length: m }, () => Array(n).fill(0));
11+
mx[0][0] = mn[0][0] = grid[0][0];
12+
13+
// initialize the top and left sides
14+
for (let i = 1; i < m; i++) {
15+
mn[i][0] = mx[i][0] = mx[i - 1][0] * grid[i][0];
16+
}
17+
for (let j = 1; j < n; j++) {
18+
mn[0][j] = mx[0][j] = mx[0][j - 1] * grid[0][j];
19+
}
20+
21+
for (let i = 1; i < m; i++) {
22+
for (let j = 1; j < n; j++) {
23+
if (grid[i][j] < 0) {
24+
// smallest negative * negative number = largest
25+
mx[i][j] = Math.min(mn[i - 1][j], mn[i][j - 1]) * grid[i][j];
26+
mn[i][j] = Math.max(mx[i - 1][j], mx[i][j - 1]) * grid[i][j];
27+
} else {
28+
// largest product * positive number = largest
29+
mx[i][j] = Math.max(mx[i - 1][j], mx[i][j - 1]) * grid[i][j];
30+
mn[i][j] = Math.min(mn[i - 1][j], mn[i][j - 1]) * grid[i][j];
31+
}
32+
}
33+
}
34+
35+
let ans = mx[m - 1][n - 1] % MOD;
36+
return ans < 0 ? -1 : ans;
37+
};

0 commit comments

Comments
 (0)