Maximum Non Negative Product in a Matrix - Problem
You're navigating through a numerical matrix from the top-left corner to the bottom-right corner, but there's a catch - you can only move right or down!
Your goal is to find the path that gives you the maximum non-negative product by multiplying all the numbers you encounter along your journey. If all possible paths result in negative products, return -1.
Key Points:
- Start at position
(0, 0)and reach(m-1, n-1) - Only move right or down in each step
- Calculate the product of all numbers in your path
- Return the maximum non-negative product modulo
10^9 + 7 - If no non-negative product exists, return
-1
Example: In a 2x3 grid [[1, -2, 1], [1, -1, 1]], the optimal path might be 1 → 1 → -1 → 1 = -1, but we need to find the best non-negative path!
Input & Output
example_1.py — Basic Negative Path
$
Input:
[[-1,-2,-3],[-2,-3,-3],[-3,-3,-2]]
›
Output:
18
💡 Note:
The optimal path is (-1) × (-2) × (-3) × (-3) = 18. Even though we start with negative numbers, multiplying negatives can create positive products.
example_2.py — Mixed Values
$
Input:
[[1,-2,1],[1,-1,1]]
›
Output:
1
💡 Note:
The best path is 1 → 1 → 1 → 1 = 1, avoiding the negative numbers entirely when possible to maintain a positive product.
example_3.py — All Negative Result
$
Input:
[[1,3],[0,-4]]
›
Output:
-1
💡 Note:
Any path through this matrix will include the 0, making the final product 0. Since 0 is non-negative but we want maximum non-negative, and other paths are negative, we return -1.
Constraints
- m == grid.length
- n == grid[i].length
- 1 ≤ m, n ≤ 15
- -4 ≤ grid[i][j] ≤ 4
- Important: The answer is guaranteed to fit in a 32-bit integer
Visualization
Tap to expand
Understanding the Visualization
1
Setup DP Tables
Create matrices to track maximum and minimum products at each position
2
Initialize Boundaries
Fill first row and column with cumulative products
3
Process Each Cell
For positive numbers, max stays max, min stays min. For negative numbers, they swap!
4
Extract Result
Return the maximum product from bottom-right cell, or -1 if negative
Key Takeaway
🎯 Key Insight: By tracking both maximum and minimum products at each step, we can handle the sign-flipping nature of negative number multiplication to find optimal paths that might not be obvious at first glance.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code