Python 1594.py
class Solution:
def maxProductPath(self, grid: List[List[int]]) -> int:
@cache
def deeper(x, y): # analyze path in reverse: from bottom-right to upper-left
value = grid[y][x]
if x == 0 and y == 0:
return [ value, value ]
if value == 0: # actually there is no need to handle this edge case ...
return [ 0, 0 ]
high = -inf
low = +inf
if x > 0: # go left
h, l = deeper(x - 1, y)
h *= value
l *= value
high, low = max(high, h, l), min(low, h, l)
if y > 0: # go up
h, l = deeper(x, y - 1)
h *= value
l *= value
high, low = max(high, h, l), min(low, h, l)
# if value is negative, then high and low must be swapped
return [ high, low ]
height = len(grid)
width = len(grid[0])
high, low = deeper(width - 1, height - 1)
return high % 1_000_000_007 if high >= 0 else -1
Difficulty
and has an acceptance rate of about 52% (200k+ submissions).
Typical patterns to solve this problem:
- Array
- Dynamic Programming
- Matrix
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation defines a Solution class with a method maxProductPath that determines the greatest possible product of values along any path from the top-left corner to the bottom-right corner of a rectangular integer grid. Movement is restricted to rightward or downward steps. The method returns the maximal product modulo 1 000 000 007 when the product is non-negative; otherwise it returns -1.
Core Logic
Recursive dynamic programming with memoization
The heart of the algorithm is the nested function deeper, decorated with @cache. This decorator stores the result of each call keyed by its coordinates, guaranteeing that each cell’s computation is performed only once. The function works backward: it evaluates the best and worst products that can reach a given cell (x, y) when the traversal proceeds from the origin toward that cell.
@cache
def deeper(x, y):
value = grid[y][x]
if x == 0 and y == 0:
return [value, value]
if value == 0:
return [0, 0]
high = -inf
low = +inf
if x > 0:
h, l = deeper(x - 1, y)
h *= value
l *= value
high, low = max(high, h, l), min(low, h, l)
if y > 0:
h, l = deeper(x, y - 1)
h *= value
l *= value
high, low = max(high, h, l), min(low, h, l)
return [high, low]
The function returns a two-element list: the first element is the maximum product achievable to reach (x, y), and the second is the minimum product (which may be negative). Maintaining both extremes is essential because a subsequent negative grid value can turn a minimal (negative) product into a new maximum.
Base cases
When the recursion reaches the origin (0, 0), the only product possible is the value of that cell itself, so both the maximum and minimum are set to value. A separate early return for a cell containing 0 yields [0, 0], because any path that includes a zero collapses the product to zero, and both extremes become zero.
Transition from neighboring cells
For any other cell, the algorithm examines the two possible predecessors: the cell to the left (x-1, y) and the cell above (x, y-1). It retrieves their stored maximum and minimum products, multiplies each by the current cell’s value, and then updates the running high and low with the greatest and smallest among the newly computed candidates. This logic automatically accounts for sign changes: multiplying a negative value with the predecessor’s minimum (most negative) product can produce a new maximum, and vice versa.
Final aggregation and result
After defining deeper, the method computes the dimensions of the grid, invokes deeper for the bottom-right corner, and extracts the maximal product. If this product is non-negative, it is reduced modulo 1 000 000 007 before being returned; otherwise the method returns -1 to indicate that no non-negative product path exists.
height = len(grid)
width = len(grid[0])
high, low = deeper(width - 1, height - 1)
return high % 1_000_000_007 if high >= 0 else -1
Edge Cases Handled
The algorithm explicitly addresses cells that contain 0. By returning [0, 0] for such cells, it ensures that any path passing through a zero yields a product of zero, preventing propagation of undefined or infinite values.
Negative numbers are accommodated through the dual tracking of high and low. When a negative grid entry is encountered, the multiplication of the current value with the predecessor’s minimum (most negative) product can flip the sign, potentially creating a new maximum. The max and min operations after each neighbor’s contribution guarantee that the correct extreme values are retained regardless of sign changes.
The base case at the origin also covers the situation where the starting cell itself is zero or negative, establishing correct initial extremes for the subsequent recursion.
Performance Optimizations
The use of the @cache decorator provides memoization, turning the naïve exponential recursion into a linear-time computation relative to the number of cells. Each cell’s result is stored after the first calculation, and any later request for the same coordinates retrieves the cached pair instantly, eliminating redundant work.
By returning only two scalar values per cell (maximum and minimum), the algorithm avoids constructing larger data structures, keeping the per-cell memory footprint minimal.
The recursion proceeds in a depth-first manner but never exceeds the grid’s dimensions, so the call stack depth is bounded by the sum of width and height, which is safe for typical input sizes.
Overall, the combination of memoization, compact state representation, and bounded recursion yields an efficient solution that scales well with the size of the input grid.
ELI5 - Simplified Explanation
Imagine a big square grid filled with boxes, and each box has a secret number inside. A little explorer wants to walk from the top left corner all the way to the bottom right corner, moving only right or down. As the explorer walks, they pick up numbers from every box and multiply them together to keep track of a total score. Because some numbers are negative, they might shrink the score or make it huge, so the explorer remembers both the biggest possible score and the smallest possible score at every single step.
The code starts at the very end of the trail in the bottom right corner and looks back at where it came from. It checks the boxes to the left and the boxes above to see which paths lead to the best scores. If the explorer finds a zero in a box, everything turns into zero, which is like a speed bump. By looking at all the choices step by step and remembering the results, the explorer keeps track of the highest and lowest values possible. Once the explorer reaches the start, the math is already done, and the biggest score is found.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | ||||||||
|---|---|---|---|---|---|---|---|---|
| author | solutions | |||||||
| www | AlgoMonster | C++ | Python | Java | TS | |||
| WalkCCC | C++ | Java | ||||||
| leetcode.ca | C++ | Python | Java | Go | Rust | TS | ||
| Progiez | C++ | Python | Java | |||||
| github | black-shadows | C++ | ||||||
| charles-wangkai | Java | |||||||
| everthis | JS | |||||||
| fsq | C++ | |||||||
| JoshCrozier | JS | |||||||
| keineahnung2345 | C++ | |||||||
| lkwq007 | Python | |||||||
| wisdompeak | C++ | |||||||
| withaarzoo | C++ | |||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||
| WalkCCC | C++, Java | |||||||
| leetcode.ca | C++, Go, Java, Python, Rust, TypeScript | |||||||
| Progiez | C++, Java, Python | |||||||
| black-shadows | C++, C++ | |||||||
| charles-wangkai | Java | |||||||
| everthis | JavaScript | |||||||
| fsq | C++ | |||||||
| JoshCrozier | JavaScript | |||||||
| keineahnung2345 | C++ | |||||||
| lkwq007 | Python | |||||||
| wisdompeak | C++ | |||||||
| withaarzoo | C++ |
Videos
Solved On The Same Day
- problem 1976: Number of Ways to Arrive at Destination
- problem 3147: Taking Maximum Energy From the Mystic Dungeon
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality