MediumNo. 1594

Maximum Non Negative Product in a Matrix — LeetCode 1594 Python Solution

Topics
Array, Dynamic Programming, Matrix
Reading time
4 min

The problem

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.

Example

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.

Python solution

PythonSolution
class Solution:
    def maxProductPath(self, grid: List[List[int]]) -> int:
        m, n = len(grid), len(grid[0])
        mod = 10**9 + 7
        dp = [[[grid[0][0]] * 2 for _ in range(n)] for _ in range(m)]
        for i in range(1, m):
            dp[i][0] = [dp[i - 1][0][0] * grid[i][0]] * 2
        for j in range(1, n):
            dp[0][j] = [dp[0][j - 1][0] * grid[0][j]] * 2
        for i in range(1, m):
            for j in range(1, n):
                v = grid[i][j]
                if v >= 0:
                    dp[i][j][0] = min(dp[i - 1][j][0], dp[i][j - 1][0]) * v
                    dp[i][j][1] = max(dp[i - 1][j][1], dp[i][j - 1][1]) * v
                else:
                    dp[i][j][0] = max(dp[i - 1][j][1], dp[i][j - 1][1]) * v
                    dp[i][j][1] = min(dp[i - 1][j][0], dp[i][j - 1][0]) * v
        ans = dp[-1][-1][1]
        return -1 if ans < 0 else ans % mod

Complexity

Time
O(n·m) (typical)
Space · auxiliary
O(n·m)or optimized

Pattern: Matrix and Grid

Treat a 2-D grid as a graph whose neighbours are the four adjacent cells. LeetCode 1594. Maximum Non Negative Product in a Matrix is filed here because LeetCode tags it Matrix, which is the vocabulary this hub collects.

The matrix and grid guide has the Python template for the pattern and the 216 LeetCode problems that use it.

Related problems

Related problems
No.ProblemDifficulty
1595Minimum Cost to Connect Two Groups of PointsHard
0063Unique Paths IIMedium
0064Minimum Path SumMedium
0085Maximal RectangleHard
0174Dungeon GameHard
0221Maximal SquareMedium

Frequently asked questions

How hard is LeetCode 1594. Maximum Non Negative Product in a Matrix?

LeetCode 1594. Maximum Non Negative Product in a Matrix is rated Medium on LeetCode.

What topics does LeetCode 1594. Maximum Non Negative Product in a Matrix cover?

LeetCode 1594. Maximum Non Negative Product in a Matrix is tagged Array, Dynamic Programming and Matrix on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.