Maximum Non Negative Product in a Matrix LeetCode solution in Java

1
class Solution {
2
public class Pair {
3
long min = Integer.MAX_VALUE, max = Integer.MIN_VALUE;
4

5
Pair() {}
6

7
Pair(long min, long max) {
8
this.min = min;
9
this.max = max;
10
}
11
}
12

13
public int maxProductPath(int[][] grid) {
14
Pair[][] dp = new Pair[grid.length][grid[0].length];
15
for (int r = grid.length - 1; r >= 0; r--) {
16
for (int c = grid[0].length - 1; c >= 0; c--) {
17
if (r == grid.length - 1 && c == grid[0].length - 1) {
18
dp[r][c] = new Pair(grid[r][c], grid[r][c]);
19
} else {
20
Pair hor = (c == grid[0].length - 1) ? new Pair() : dp[r][c + 1];
21
Pair ver = (r == grid.length - 1) ? new Pair() : dp[r + 1][c];
22
long min, max;
23
if (grid[r][c] >= 0) {
24
max = Math.max(hor.max, ver.max);
25
min = Math.min(hor.min, ver.min);
26
} else {
27
min = Math.max(hor.max, ver.max);
28
max = Math.min(hor.min, ver.min);
29
}
30
dp[r][c] = new Pair(min * grid[r][c], max * grid[r][c]);
31
}
32
}
33
}
34
int mod = (int) 1e9 + 7;
35
return dp[0][0].max < 0 ? -1 : (int) (dp[0][0].max % mod);
36
}
37
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0