# [leetcode] 1594. Maximum Non Negative Product in a Matrix

## Description

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

## 分析

dp_max[i][j]=max(dp_max[i-1][j]*grid[i][j],dp_max[i][j-1]*grid[i][j])
dp_max[i][j]=max(dp_max[i][j],dp_min[i-1][j]*grid[i][j],dp_min[i][j-1]*grid[i][j])
dp_min[i][j]=min(dp_max[i-1][j]*grid[i][j],dp_max[i][j-1]*grid[i][j])
dp_min[i][j]=min(dp_min[i][j],dp_min[i-1][j]*grid[i][j],dp_min[i][j-1]*grid[i][j])


## 代码

class Solution:
def maxProductPath(self, grid: List[List[int]]) -> int:
row=len(grid)
col=len(grid[0])
dp_max=[[0]*col for i in range(row)]
dp_min=[[0]*col for i in range(row)]
dp_max[0][0]=dp_min[0][0]=grid[0][0]
for i in range(1,row):
dp_max[i][0]=dp_max[i-1][0]*grid[i][0]
dp_min[i][0]=dp_min[i-1][0]*grid[i][0]

for i in range(1,col):
dp_max[0][i]=dp_max[0][i-1]*grid[0][i]
dp_min[0][i]=dp_min[0][i-1]*grid[0][i]

for i in range(1,row):
for j in range(1,col):
dp_max[i][j]=max(dp_max[i-1][j]*grid[i][j],dp_max[i][j-1]*grid[i][j])
dp_max[i][j]=max(dp_max[i][j],dp_min[i-1][j]*grid[i][j],dp_min[i][j-1]*grid[i][j])
dp_min[i][j]=min(dp_max[i-1][j]*grid[i][j],dp_max[i][j-1]*grid[i][j])
dp_min[i][j]=min(dp_min[i][j],dp_min[i-1][j]*grid[i][j],dp_min[i][j-1]*grid[i][j])
if(dp_max[row-1][col-1]>=0):
return dp_max[row-1][col-1]%(10**9+7)
return -1


## 参考文献

1594 矩阵的最大非负积（动态规划）

• 点赞
• 评论
• 分享
x

海报分享

扫一扫，分享海报

• 收藏
• 打赏

打赏

农民小飞侠

你的鼓励将是我创作的最大动力

C币 余额
2C币 4C币 6C币 10C币 20C币 50C币
• 举报
• 一键三连

点赞Mark关注该博主, 随时了解TA的最新博文

12-27 341
09-11 313
06-06 3996
04-04 202
08-04 893
04-08 1934
06-20 4089
12-18
12-20
09-18