LeetCode 1594. Maximum Non Negative Product in a Matrix Solution in Java, C++, Python & More | Explanation + Code

CoderIndeed
0
1594. Maximum Non Negative Product in a Matrix

Description

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.

 

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.length
  • n == grid[i].length
  • 1 <= m, n <= 15
  • -4 <= grid[i][j] <= 4

Solutions

Solution 1: Dynamic Programming

We define a 3D array f, where f[i][j][0] and f[i][j][1] represent the minimum and maximum product of all paths from the top-left corner (0, 0) to position (i, j), respectively. For each position (i, j), we can transition from above (i - 1, j) or from the left (i, j - 1), so we need to consider the results of multiplying the minimum and maximum products of these two paths by the value of the current cell.

Finally, we need to return f[m - 1][n - 1][1] modulo 109 + 7. If f[m - 1][n - 1][1] is less than 0, return -1.

The time complexity is O(m × n) and the space complexity is O(m × n), where m and n are the number of rows and columns of the matrix, respectively.

PythonJavaC++GoTypeScriptRust
class Solution: def maxProductPath(self, grid: List[List[int]]) -> int: m, n = len(grid), len(grid[0]) f = [[[0, 0] for _ in range(n)] for _ in range(m)] for i in range(m): for j in range(n): x = grid[i][j] if i == 0 and j == 0: f[i][j][0] = x f[i][j][1] = x continue mn, mx = inf, -inf if i > 0: a, b = f[i - 1][j] mn = min(mn, a * x, b * x) mx = max(mx, a * x, b * x) if j > 0: a, b = f[i][j - 1] mn = min(mn, a * x, b * x) mx = max(mx, a * x, b * x) f[i][j][0], f[i][j][1] = mn, mx ans = f[m - 1][n - 1][1] mod = 10**9 + 7 return -1 if ans < 0 else ans % mod(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !