-
Notifications
You must be signed in to change notification settings - Fork 0
/
1594. Maximum Non Negative Product in a Matrix.py
85 lines (61 loc) · 2.58 KB
/
1594. Maximum Non Negative Product in a Matrix.py
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
'''
You are given a rows x cols matrix grid. Initially, you are located at the top-left corner (0, 0), and in each step, you can only move right or down in the matrix.
Among all possible paths starting from the top-left corner (0, 0) and ending in the bottom-right corner (rows - 1, cols - 1), find the path with the maximum non-negative product. The product of a path is the product of all integers in the grid cells visited along the path.
Return the maximum non-negative product modulo 109 + 7. If the maximum product is negative return -1.
Notice that the modulo is performed after getting the maximum product.
Example 1:
Input: grid = [[-1,-2,-3],
[-2,-3,-3],
[-3,-3,-2]]
Output: -1
Explanation: It's not possible to get non-negative product in the path from (0, 0) to (2, 2), so return -1.
Example 2:
Input: grid = [[1,-2,1],
[1,-2,1],
[3,-4,1]]
Output: 8
Explanation: Maximum non-negative product is in bold (1 * 1 * -2 * -4 * 1 = 8).
Example 3:
Input: grid = [[1, 3],
[0,-4]]
Output: 0
Explanation: Maximum non-negative product is in bold (1 * 0 * -4 = 0).
Example 4:
Input: grid = [[ 1, 4,4,0],
[-2, 0,0,1],
[ 1,-1,1,1]]
Output: 2
Explanation: Maximum non-negative product is in bold (1 * -2 * 1 * -1 * 1 * 1 = 2).
Constraints:
1 <= rows, cols <= 15
-4 <= grid[i][j] <= 4
'''
class Solution:
def maxProductPath(self, grid):
n = len(grid)
m = len(grid[0])
maxp = [[0 for i in range(m)] for j in range(n)]
minp = [[0 for i in range(m)] for j in range(n)]
for i in range(n):
for j in range(m):
minv = 2**31-1
maxv = -2**31
if i==0 and j==0:
maxv = grid[i][j]
minv = grid[i][j]
if i>0:
tmax = max(maxp[i - 1][j] * grid[i][j], minp[i - 1][j] * grid[i][j]);
maxv = max(maxv, tmax)
tmin = min(maxp[i - 1][j] * grid[i][j], minp[i - 1][j] * grid[i][j]);
minv = min(minv, tmin)
if (j > 0):
tmax = max(maxp[i][j - 1] * grid[i][j], minp[i][j - 1] * grid[i][j]);
maxv = max(maxv, tmax)
tmin = min(maxp[i][j - 1] * grid[i][j], minp[i][j - 1] * grid[i][j]);
minv = min(minv, tmin)
maxp[i][j] = maxv
minp[i][j] = minv
if maxp[-1][-1]>=0:
return maxp[-1][-1]%(10**9+7)
else:
return -1