|
| 1 | +/** |
| 2 | + * 1594. Maximum Non Negative Product in a Matrix |
| 3 | + * https://leetcode.com/problems/maximum-non-negative-product-in-a-matrix/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * You are given a m x n matrix grid. Initially, you are located at the top-left corner (0, 0), |
| 7 | + * and in each step, you can only move right or down in the matrix. |
| 8 | + * |
| 9 | + * Among all possible paths starting from the top-left corner (0, 0) and ending in the bottom-right |
| 10 | + * corner (m - 1, n - 1), find the path with the maximum non-negative product. The product of a |
| 11 | + * path is the product of all integers in the grid cells visited along the path. |
| 12 | + * |
| 13 | + * Return the maximum non-negative product modulo 109 + 7. If the maximum product is negative, |
| 14 | + * return -1. |
| 15 | + * |
| 16 | + * Notice that the modulo is performed after getting the maximum product. |
| 17 | + */ |
| 18 | + |
| 19 | +/** |
| 20 | + * @param {number[][]} grid |
| 21 | + * @return {number} |
| 22 | + */ |
| 23 | +var maxProductPath = function(grid) { |
| 24 | + const rows = grid.length; |
| 25 | + const cols = grid[0].length; |
| 26 | + const dp = Array.from({ length: rows }, () => |
| 27 | + Array.from({ length: cols }, () => [1, 1]) |
| 28 | + ); |
| 29 | + |
| 30 | + dp[0][0] = [grid[0][0], grid[0][0]]; |
| 31 | + |
| 32 | + for (let row = 0; row < rows; row++) { |
| 33 | + for (let col = 0; col < cols; col++) { |
| 34 | + if (row === 0 && col === 0) continue; |
| 35 | + |
| 36 | + let minProduct = Infinity; |
| 37 | + let maxProduct = -Infinity; |
| 38 | + |
| 39 | + if (row > 0) { |
| 40 | + minProduct = Math.min( |
| 41 | + minProduct, |
| 42 | + dp[row - 1][col][0] * grid[row][col], |
| 43 | + dp[row - 1][col][1] * grid[row][col] |
| 44 | + ); |
| 45 | + maxProduct = Math.max( |
| 46 | + maxProduct, |
| 47 | + dp[row - 1][col][0] * grid[row][col], |
| 48 | + dp[row - 1][col][1] * grid[row][col] |
| 49 | + ); |
| 50 | + } |
| 51 | + |
| 52 | + if (col > 0) { |
| 53 | + minProduct = Math.min( |
| 54 | + minProduct, |
| 55 | + dp[row][col - 1][0] * grid[row][col], |
| 56 | + dp[row][col - 1][1] * grid[row][col] |
| 57 | + ); |
| 58 | + maxProduct = Math.max( |
| 59 | + maxProduct, |
| 60 | + dp[row][col - 1][0] * grid[row][col], |
| 61 | + dp[row][col - 1][1] * grid[row][col] |
| 62 | + ); |
| 63 | + } |
| 64 | + |
| 65 | + dp[row][col] = [minProduct, maxProduct]; |
| 66 | + } |
| 67 | + } |
| 68 | + |
| 69 | + const maxResult = dp[rows - 1][cols - 1][1]; |
| 70 | + return maxResult < 0 ? -1 : maxResult % (10 ** 9 + 7); |
| 71 | +}; |
0 commit comments