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 modulo109 + 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: Dynamic Programming
- Time complexity: O(mn)
- Space complexity: O(mn)
JavaScript
js
/**
* @param {number[][]} grid
* @return {number}
*/
const maxProductPath = function (grid) {
const MODULO = 10 ** 9 + 7;
const m = grid.length;
const n = grid[0].length;
const dpMax = new Array(m)
.fill('')
.map(_ => new Array(n).fill(0));
const dpMin = new Array(m)
.fill('')
.map(_ => new Array(n).fill(0));
for (let row = 0; row < m; row++) {
for (let col = 0; col < n; col++) {
const value = grid[row][col];
const maxUpValue = dpMax[row - 1]?.[col] * value;
const maxLeftValue = dpMax[row][col - 1] * value;
const minUpValue = dpMin[row - 1]?.[col] * value;
const minLeftValue = dpMin[row][col - 1] * value;
if (row === 0 && col === 0) {
dpMax[row][col] = dpMin[row][col] = grid[0][0];
} else if (row === 0) {
dpMax[row][col] = Math.max(maxLeftValue, minLeftValue);
dpMin[row][col] = Math.min(maxLeftValue, minLeftValue);
} else if (col === 0) {
dpMax[row][col] = Math.max(maxUpValue, minUpValue);
dpMin[row][col] = Math.min(maxUpValue, minUpValue);
} else {
const maxUp = Math.max(maxUpValue, minUpValue);
const maxLeft = Math.max(maxLeftValue, minLeftValue);
const minUp = Math.min(maxUpValue, minUpValue);
const minLeft = Math.min(maxLeftValue, minLeftValue);
dpMax[row][col] = Math.max(maxUp, maxLeft);
dpMin[row][col] = Math.min(minUp, minLeft);
}
}
}
return dpMax[m - 1][n - 1] < 0 ? -1 : dpMax[m - 1][n - 1] % MODULO;
};