#1594
Maximum Non Negative Product in a Matrix
MediumArrayDynamic ProgrammingMatrixDynamic ProgrammingMatrix Traversal
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(2^(m+n)) | O(m * n) |
| Space | O(m+n) | O(m * n) |
💡
Intuition
Time O(m * n)Space O(m * n)
In the optimal solution, we use dynamic programming to keep track of both the maximum and minimum products at each cell. This allows us to efficiently calculate the maximum non-negative product while considering the effects of negative numbers.
⚙️
Algorithm
4 steps- 1Step 1: Create two matrices, maxProd and minProd, to store the maximum and minimum products up to each cell.
- 2Step 2: Initialize the starting point (0, 0) in both matrices with the value of grid[0][0].
- 3Step 3: Iterate through each cell in the grid, updating maxProd and minProd based on the values from the top and left cells.
- 4Step 4: At the end, check the value in maxProd at the bottom-right corner. If it's negative, return -1; otherwise, return maxProd[m-1][n-1] % (10^9 + 7).
solution.py25 lines
1# Full working Python code
2from typing import List
3
4def maxNonNegativeProduct(grid: List[List[int]]) -> int:
5 MOD = 10**9 + 7
6 m, n = len(grid), len(grid[0])
7 maxProd = [[0] * n for _ in range(m)]
8 minProd = [[0] * n for _ in range(m)]
9 maxProd[0][0] = minProd[0][0] = grid[0][0]
10
11 for i in range(m):
12 for j in range(n):
13 if i == 0 and j == 0: continue
14 max_val, min_val = float('-inf'), float('inf')
15 if i > 0:
16 max_val = max(max_val, maxProd[i-1][j] * grid[i][j])
17 min_val = min(min_val, minProd[i-1][j] * grid[i][j])
18 if j > 0:
19 max_val = max(max_val, maxProd[i][j-1] * grid[i][j])
20 min_val = min(min_val, minProd[i][j-1] * grid[i][j])
21 maxProd[i][j] = max_val
22 minProd[i][j] = min_val
23
24 result = maxProd[m-1][n-1]
25 return result % MOD if result >= 0 else -1ℹ
Complexity note: The time complexity is linear with respect to the number of cells in the grid, as we visit each cell once. The space complexity is also linear due to the storage of two matrices.
- 1Dynamic programming is essential for optimizing path problems in grids.
- 2Tracking both maximum and minimum products helps handle negative numbers effectively.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.