Cherry Pickup II — LeetCode 1463 Python Solution

HardArrayDynamic ProgrammingMatrix
Problem
#1463
Reading time
3 min

The problem

You are given a rows x cols matrix grid representing a field of cherries where grid[i][j] represents the number of cherries that you can collect from the (i, j) cell. You have two robots that can collect cherries for you: Robot #1 is located at the top-left corner (0, 0), and Robot #2 is located at the top-right corner (0, cols - 1).

Example

Input
grid = [[3,1,1],[2,5,1],[1,5,5],[2,1,1]]
Output
24
Explanation
Path of robot #1 and #2 are described in color green and blue respectively.

Python solution

Python
class Solution:
    def cherryPickup(self, grid: List[List[int]]) -> int:
        m, n = len(grid), len(grid[0])
        f = [[[-1] * n for _ in range(n)] for _ in range(m)]
        f[0][0][n - 1] = grid[0][0] + grid[0][n - 1]
        for i in range(1, m):
            for j1 in range(n):
                for j2 in range(n):
                    x = grid[i][j1] + (0 if j1 == j2 else grid[i][j2])
                    for y1 in range(j1 - 1, j1 + 2):
                        for y2 in range(j2 - 1, j2 + 2):
                            if 0 <= y1 < n and 0 <= y2 < n and f[i - 1][y1][y2] != -1:
                                f[i][j1][j2] = max(f[i][j1][j2], f[i - 1][y1][y2] + x)
        return max(f[-1][j1][j2] for j1, j2 in product(range(n), range(n)))

Complexity

MeasureComplexity
TimeO(m \times n^2)
SpaceO(m \times n^2) auxiliary

Pattern: Matrix and Grid

Treat a 2-D grid as a graph whose neighbours are the four adjacent cells. LeetCode 1463. Cherry Pickup II 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

Frequently asked questions

How hard is LeetCode 1463. Cherry Pickup II?
LeetCode 1463. Cherry Pickup II is rated Hard on LeetCode.
What is the time complexity of LeetCode 1463. Cherry Pickup II?
The Python solution on this page runs in O(m \times n^2).
What is the space complexity of LeetCode 1463. Cherry Pickup II?
The Python solution on this page uses O(m \times n^2) auxiliary space.
What topics does LeetCode 1463. Cherry Pickup II cover?
LeetCode 1463. Cherry Pickup II 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.

Get Stealth Interview