The Maximum Non Negative Product in a Matrix coding problem gives you an m×n grid of integers. You must travel from the top-left to the bottom-right cell, only moving right or down. Along the path, multiply all values encountered. Find the maximum non-negative product of any such path, modulo 10^9 + 7. If no non-negative product path exists, return -1.
Amazon and Google use this problem because it combines a classic path DP with the tricky aspect of tracking both maximum and minimum products simultaneously. Negative numbers are key: multiplying two negatives gives a positive, so the current minimum might become the future maximum. This dual-tracking pattern is a hallmark of product-based DP problems.
Dynamic Programming with dual tracking: At each cell, maintain both the maximum and minimum product of paths reaching that cell. The transition is: when the cell value is positive, max comes from multiplying max with the cell; min comes from multiplying min. When negative: max might come from previous min * negative (two negatives = positive), and vice versa. At the destination, if max_product >= 0, return max_product % MOD; otherwise return -1.
Be careful: take modulo only at the final step, not intermediately, since comparing products mid-computation requires actual (not modded) values.
Grid: [[1, -2, 1], [1, -2, 1], [3, -4, 1]]
Paths (right/down only):
Track max/min at each cell:
Answer = 8.
For the Array Matrix Dynamic Programming interview pattern, the "track max and min simultaneously" trick applies to any DP with multiplication over potentially negative values. Practice it first on 1D arrays (maximum product subarray), then extend to 2D grids. The swap-on-negative step is the critical implementation detail to master.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Maximum Number of Moves in a Grid | Medium | Solve | |
| Bomb Enemy | Medium | Solve | |
| Check if There is a Path With Equal Number of 0's And 1's | Medium | Solve | |
| Longest Line of Consecutive One in Matrix | Medium | Solve | |
| Minimum Path Cost in a Grid | Medium | Solve |