Leetcode 1594: Maximum Non Negative Product in a Matrix

grid47
grid47
Exploring patterns and algorithms
May 31, 2024 8 min read

You are given a m x n matrix grid. Starting at the top-left corner (0, 0), you can only move right or down. Your task is to find the path from the top-left to the bottom-right corner that results in the maximum non-negative product of the grid values along the path. If such a path results in a negative product, return -1. The product is calculated by multiplying all grid values visited along the path. You should return the maximum non-negative product modulo 10^9 + 7.
Problem
Approach
Steps
Complexity
Input: You are given a matrix grid of size m x n where each element is an integer between -4 and 4, inclusive.
Example: Input: grid = [[1,-2,1],[1,-2,1],[3,-4,1]]
Constraints:
• 1 <= m, n <= 15
• -4 <= grid[i][j] <= 4
Output: Return the maximum non-negative product modulo 10^9 + 7. If the maximum product is negative, return -1.
Example: Output: 8
Constraints:
• The answer should be modulo 10^9 + 7.
Goal: The goal is to find the path from the top-left to the bottom-right corner that results in the maximum non-negative product.
Steps:
• 1. Use depth-first search (DFS) to explore all possible paths from (0, 0) to (m - 1, n - 1).
• 2. At each position, compute the product of the path visited so far and update the result if a higher non-negative product is found.
• 3. Use memoization to store intermediate results and avoid redundant calculations.
Goal: Ensure the solution works for grid sizes within the given constraints, i.e., m and n are both between 1 and 15.
Steps:
• 1 <= m, n <= 15
• Each grid cell contains an integer between -4 and 4.
Assumptions:
• The grid is not empty and has at least one element.
• You can only move right or down from any cell.
Input: Input: grid = [[1,-2,1],[1,-2,1],[3,-4,1]]
Explanation: The path that yields the maximum non-negative product is (1 -> 1 -> -2 -> -4 -> 1), resulting in a product of 8. Hence, the output is 8.

Input: Input: grid = [[1,3],[0,-4]]
Explanation: The path yielding the maximum non-negative product is (1 -> 0 -> -4), which results in a product of 0. Hence, the output is 0.

Input: Input: grid = [[-1,-2,-3],[-2,-3,-3],[-3,-3,-2]]
Explanation: In this case, all possible paths result in a negative product. Therefore, the output is -1.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus