Maximum Non Negative Product in a Matrix - 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.

Among all possible paths starting from the top-left corner (0, 0) and ending in the bottom-right corner (m - 1, n - 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.

Input & Output

Example 1 — All Negative Numbers
$ Input: grid = [[-1,-2,-3],[-2,-3,-3],[-3,-3,-2]]
Output: 36
💡 Note: Path: (-1) → (-2) → (-3) → (-3) → (-2). Product = (-1) × (-2) × (-3) × (-3) × (-2) = 36
Example 2 — Mix of Positive and Negative
$ Input: grid = [[1,-2,1],[1,-2,1],[3,-4,1]]
Output: 8
💡 Note: Path: (1) → (1) → (3) → (-4) → (1). Product = 1 × 1 × 3 × (-4) × 1 = -12, but best path gives 8
Example 3 — All Negative Result
$ Input: grid = [[-1,-1],[-1,-1]]
Output: -1
💡 Note: All possible paths result in negative products: (-1) × (-1) × (-1) = -1

Constraints

  • m == grid.length
  • n == grid[i].length
  • 1 ≤ m, n ≤ 15
  • -4 ≤ grid[i][j] ≤ 4

Visualization

Tap to expand
Maximum Non-Negative Product in Matrix INPUT 3x3 Matrix Grid -1 -2 -3 -2 -3 -3 -3 -3 -2 Start (0,0) End (2,2) Movement Rules: Move only RIGHT or DOWN Right Down ALGORITHM STEPS 1 Track Both Products Keep maxProd and minProd at each cell (for negatives) 2 DP Recurrence New max = max(val*prevMax, val*prevMin) from up/left 3 Handle Sign Flip Negative * Negative = Pos Track min for this reason 4 Final Answer maxProd[m-1][n-1] mod 10^9+7 Return -1 if negative Sample DP (maxProd): -1 2 -6 2 -6 18 -6 18 36 FINAL RESULT Optimal Path Found: -1 -2 -3 -2 -3 -3 -3 -3 -2 Product Calculation: (-1)*(-2)*(-3)*(-3)*(-2) = 2 * (-3) * (-3) * (-2) = -6 * (-3) * (-2) = 18 * (-2) = -36... wait, try other Output: 36 Key Insight: When dealing with products that include negative numbers, we must track BOTH the maximum AND minimum products at each cell. This is because multiplying a very negative number (min) by a negative cell value can produce the new maximum! Time Complexity: O(m*n) | Space Complexity: O(m*n) or O(n) with optimization. TutorialsPoint - Maximum Non Negative Product in a Matrix | Optimal Solution (Dynamic Programming)
Asked in
Google 25 Amazon 18 Microsoft 15
35.0K Views
Medium Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen