Maximum Non Negative Product in a Matrix

You are given an 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 10^9 + 7. If the maximum product is negative, return -1.

Notice that the modulo is performed after getting the maximum product.

Example 1
-1 -2 -3
-2 -3 -3
-3 -3 -2
Inputgrid = [[-1,-2,-3],[-2,-3,-3],[-3,-3,-2]]
Output-1
It is not possible to get non-negative product in the path from (0, 0) to (2, 2), so return -1.
Example 2
 1 -2  1
 1 -2  1
 3 -4  1
Inputgrid = [[1,-2,1],[1,-2,1],[3,-4,1]]
Output8
The maximum non-negative product is 1 * 1 * -2 * -4 * 1 = 8.

Constraints

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

Asked at 3 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate