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 MatrixInput Matrix-1-2-3-2-3-3Optimal Path-1-2-3-2-3-3Path: (-1) → (-2) → (-3) → (-3) → (-3)Product: (-1) × (-2) × (-3) × (-3) × (-3) = -54 ❌Better Path: (-1) → (-2) → (-3) → (-3) → (-2) = 36 ✓Maximum Non-Negative Product: 36
Understanding the Visualization
1
Input Matrix
Matrix with positive and negative numbers
2
Find Paths
Only right and down moves allowed
3
Calculate Products
Track maximum non-negative product
Key Takeaway
🎯 Key Insight: Negative numbers can create positive products when multiplied together - track both max and min values!
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