Maximum Non Negative Product in a Matrix — LeetCode 1594 Python Solution
MediumArrayDynamic ProgrammingMatrix
- Problem
- #1594
- Pattern
- Matrix and Grid
- Reading time
- 4 min
- Source
- leetcode.com
The problem
You are given a m x n 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.
Example
- Input
- grid = [[-1,-2,-3],[-2,-3,-3],[-3,-3,-2]]
- Output
- -1
- Explanation
- It is not possible to get non-negative product in the path from (0, 0) to (2, 2), so return -1.
Python solution
Python
class Solution:
def maxProductPath(self, grid: List[List[int]]) -> int:
m, n = len(grid), len(grid[0])
mod = 10**9 + 7
dp = [[[grid[0][0]] * 2 for _ in range(n)] for _ in range(m)]
for i in range(1, m):
dp[i][0] = [dp[i - 1][0][0] * grid[i][0]] * 2
for j in range(1, n):
dp[0][j] = [dp[0][j - 1][0] * grid[0][j]] * 2
for i in range(1, m):
for j in range(1, n):
v = grid[i][j]
if v >= 0:
dp[i][j][0] = min(dp[i - 1][j][0], dp[i][j - 1][0]) * v
dp[i][j][1] = max(dp[i - 1][j][1], dp[i][j - 1][1]) * v
else:
dp[i][j][0] = max(dp[i - 1][j][1], dp[i][j - 1][1]) * v
dp[i][j][1] = min(dp[i - 1][j][0], dp[i][j - 1][0]) * v
ans = dp[-1][-1][1]
return -1 if ans < 0 else ans % modComplexity
| Measure | Complexity |
|---|---|
| Time | O(n·m) (typical) |
| Space | O(n·m) or optimized auxiliary |
Pattern: Matrix and Grid
Treat a 2-D grid as a graph whose neighbours are the four adjacent cells. LeetCode 1594. Maximum Non Negative Product in a Matrix is filed here because LeetCode tags it Matrix, which is the vocabulary this hub collects.
The matrix and grid guide has the Python template for the pattern and the 216 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 1594. Maximum Non Negative Product in a Matrix?
- LeetCode 1594. Maximum Non Negative Product in a Matrix is rated Medium on LeetCode.
- What topics does LeetCode 1594. Maximum Non Negative Product in a Matrix cover?
- LeetCode 1594. Maximum Non Negative Product in a Matrix is tagged Array, Dynamic Programming and Matrix on LeetCode.