forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 14
/
maximum-non-negative-product-in-a-matrix.cpp
30 lines (29 loc) · 1.27 KB
/
maximum-non-negative-product-in-a-matrix.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
// Time: O(m * n)
// Space: O(n)
// dp with rolling window
class Solution {
public:
int maxProductPath(vector<vector<int>>& grid) {
static const int MOD = 1e9 + 7;
vector<vector<int64_t>> max_dp(2, vector<int64_t>(size(grid[0])));
vector<vector<int64_t>> min_dp(2, vector<int64_t>(size(grid[0])));
for (int i = 0; i < size(grid); ++i) {
for (int j = 0; j < size(grid[0]); ++j) {
if (i == 0 && j == 0) {
max_dp[0][0] = min_dp[0][0] = grid[0][0];
continue;
}
auto curr_max = max(i > 0 ? max_dp[(i - 1) % 2][j] : max_dp[i % 2][j - 1],
j > 0 ? max_dp[i % 2][j - 1] : max_dp[(i - 1) % 2][j]);
auto curr_min = min(i > 0 ? min_dp[(i - 1) % 2][j] : min_dp[i % 2][j - 1],
j > 0 ? min_dp[i % 2][j - 1] : min_dp[(i - 1) % 2][j]);
if (grid[i][j] < 0) {
swap(curr_max, curr_min);
}
max_dp[i % 2][j] = curr_max * grid[i][j];
min_dp[i % 2][j] = curr_min * grid[i][j];
}
}
return max_dp[(size(grid) - 1) % 2].back() >= 0 ? max_dp[(size(grid) - 1) % 2].back() % MOD : -1;
}
};