Problem Description
Given an m x n matrix grid, find a path from the top-left corner to the bottom-right corner which yields the maximum non-negative product. In each step, you are allowed to move only right or down. The product of a path is the product of all numbers encountered along that path. Return the product modulo (10^9 + 7) if it is non-negative, or -1 if no path yields a non-negative product.
Key Insights
- Use dynamic programming to track both the maximum and minimum product obtainable at each cell because negative numbers can flip the sign.
- At every cell (i, j), the possible paths come from the top (i-1, j) or left (i, j-1). For each incoming value, calculate the new products by multiplying with grid[i][j].
- Maintain a pair (maxProduct, minProduct) per cell because a very small (negative) product might become the maximum when multiplied by a negative number.
- Special care is needed for cells that are 0, as they reset the product.
- Finally, check the result at the bottom-right cell for non-negativity before applying the modulo.
Space and Time Complexity
Time Complexity: O(m * n) – We traverse each cell a constant number of times. Space Complexity: O(m * n) – Using a DP table to store the maximum and minimum products for each cell.
Solution
We use a dynamic programming approach where each cell (i, j) holds two values: the maximum product possible (dpMax) and the minimum product possible (dpMin) along any path reaching that cell. The reason for tracking both is that multiplying with a negative number can flip a minimum product into a maximum product.
For each cell, we derive the potential candidates from its top and left neighbors (if available) and then multiply them by the current cell value. Then, update the current cell’s dpMax with the maximum among these candidates and dpMin with the minimum. Special boundary handling for the first row and column is required since there’s only one direction from which they can be reached.
Finally, if the maximum product at the bottom-right cell is negative, return -1; otherwise, return the product modulo (10^9 + 7).