Maximum Non Negative Product in a Matrix Problem
Description
LeetCode Problem 1594.
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 10^9 + 7. If the maximum product is negative, return -1.
Notice that the modulo is performed after getting the maximum product.
Example 1:

Input: grid = [[-1,-2,-3],[-2,-3,-3],[-3,-3,-2]]
Output: -1
Explanation: It is not possible to get non-negative product in the path from (0, 0) to (2, 2), so return -1.
Example 2:

Input: grid = [[1,-2,1],[1,-2,1],[3,-4,1]]
Output: 8
Explanation: Maximum non-negative product is shown (1 * 1 * -2 * -4 * 1 = 8).
Example 3:

Input: grid = [[1,3],[0,-4]]
Output: 0
Explanation: Maximum non-negative product is shown (1 * 0 * -4 = 0).
Constraints:
m == grid.lengthn == grid[i].length1 <= m, n <= 15-4 <= grid[i][j] <= 4
Solution
Approach: Dynamic Programming with Max and Min
With only positive numbers we would keep the largest product reaching each cell. Negative numbers break that: the smallest (most negative) product times a negative cell can become the largest. So keep both:
hi[i][j]: the largest product of a path from(0, 0)to(i, j)lo[i][j]: the smallest product of such a path
A cell is reached from above or from the left. With x = grid[i][j], the candidates are hi and lo of those neighbours multiplied by x; hi[i][j] is the largest candidate and lo[i][j] the smallest. The first row and column have only one neighbour.
At the end, if hi[m-1][n-1] is negative, return -1; otherwise return it modulo 10^9 + 7. Take the modulo only at the end, as the statement says: comparing reduced values would be wrong. A path has at most 29 cells, so a product is at most 4^29 in absolute value, which fits in a 64-bit integer.
Complexity: O(mn) time and O(mn) extra space.
class Solution:
def maxProductPath(self, grid: List[List[int]]) -> int:
m, n = len(grid), len(grid[0])
# hi[i][j] / lo[i][j]: largest / smallest product of a path from (0, 0) to (i, j)
hi = [[0] * n for _ in range(m)]
lo = [[0] * n for _ in range(m)]
hi[0][0] = lo[0][0] = grid[0][0]
for i in range(m):
for j in range(n):
if i == 0 and j == 0:
continue
x = grid[i][j]
cands = []
if i > 0:
cands += [hi[i - 1][j] * x, lo[i - 1][j] * x]
if j > 0:
cands += [hi[i][j - 1] * x, lo[i][j - 1] * x]
hi[i][j] = max(cands)
lo[i][j] = min(cands)
best = hi[m - 1][n - 1]
return -1 if best < 0 else best % (10**9 + 7)