Cherry Pickup II (LeetCode 1463): Solution and Explanation

Hard
Array
Dynamic Programming
Matrix

Two robots start in the top row of a grid of cherries, one in the left corner and one in the right corner. Each step both move down one row and may shift one column left, right or stay. Collect the most cherries possible, counting a shared cell only once.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

Intuition

Planning the two robots separately does not work. If the first robot greedily takes its best path, it may grab cherries the second robot needed, and the best pair of paths is not the pair of best paths. A brute force over both paths is 9^rows combinations, so we need to search them together without enumerating them.

The key observation is that both robots always sit on the same row, because each move goes down exactly one row. So the full state after any number of moves is just three numbers: the row and the two columns. The future only depends on that state, not on how the robots got there, which is exactly what dynamic programming needs. Let dp[c1][c2] be the most cherries collected so far with robot one in column c1 and robot two in column c2 of the current row.

To fill the next row, each new state (c1, c2) can be reached from nine previous states, one for each pair of column shifts. Take the best reachable predecessor and add the cherries at both new cells, or just one cell when the robots share a column. The reference code goes row by row and only keeps two layers, marking unreachable states with -1. It also skips columns that a robot cannot have reached yet: robot one starts at column 0, so after row moves it is at most at column row, and robot two can be no further left than n - 1 - row.

Approach: Row by row DP over both columns

  1. Create an n × n table filled with -1 for unreachable states, and set dp[0][n - 1] to the cherries at the two starting corners.
  2. For each row from 1 to m - 1, create a fresh new_dp filled with -1.
  3. For each reachable c1 (at most row) and c2 (at least n - 1 - row), try all nine combinations of previous columns c1 - dc1 and c2 - dc2.
  4. For every predecessor that is inside the grid and reachable, compute the cherries in this row, counting grid[row][c1] and adding grid[row][c2] only when c1 != c2.
  5. Store the best total in new_dp[c1][c2], then replace dp with new_dp.
  6. After the last row, return the largest value in dp.

Step-by-step example

grid = [[3,1,1], [2,5,1], [1,5,5], [2,1,1]]
  1. Row 0: the robots start in columns 0 and 2, so dp[0][2] = 3 + 1 = 4.
  2. Row 1: for example dp[0][1] = 4 + 2 + 5 = 11 (robot one stays in column 0, robot two moves to column 1). The best state in this row is 11.
  3. Row 2: dp[1][2] takes the predecessor dp[0][1] = 11 and adds 5 + 5, giving 21, the best in this row.
  4. Row 3: dp[0][1] comes from dp[1][2] = 21 and adds 2 + 1, giving 24.
  5. The maximum over the final row is 24, matching the paths 3, 2, 5, 2 and 1, 5, 5, 1.

Code: Python, Java, C++

1class Solution:
2    def cherryPickup(self, grid: List[List[int]]) -> int:
3        m, n = len(grid), len(grid[0])
4        # dp[c1][c2] = max cherries when robot1 at col c1, robot2 at col c2
5        dp = [[-1] * n for _ in range(n)]
6        dp[0][n - 1] = grid[0][0] + (grid[0][n - 1] if n > 1 else 0)
7
8        for row in range(1, m):
9            new_dp = [[-1] * n for _ in range(n)]
10            for c1 in range(min(row + 1, n)):
11                for c2 in range(max(0, n - 1 - row), n):
12                    # Try all 9 combinations of moves
13                    for dc1 in [-1, 0, 1]:
14                        for dc2 in [-1, 0, 1]:
15                            pc1, pc2 = c1 - dc1, c2 - dc2
16                            if 0 <= pc1 < n and 0 <= pc2 < n and dp[pc1][pc2] != -1:
17                                cherries = grid[row][c1]
18                                if c1 != c2:
19                                    cherries += grid[row][c2]
20                                new_dp[c1][c2] = max(new_dp[c1][c2], dp[pc1][pc2] + cherries)
21            dp = new_dp
22
23        return max(max(row) for row in dp)

Time and space complexity

Time

O(m × n²)

There are m rows, n² column pairs per row, and a constant nine transitions per pair.

Space

O(n²)

Only the current and previous rows of the n × n table are stored.

Other approaches

Top-down recursion with memoization (time O(m × n²), space O(m × n²))

Define f(row, c1, c2) as the best total from this row to the bottom, recurse into the nine moves and cache the results. It is often quicker to write in an interview and has the same complexity, but stores the whole m × n × n cache.

Common mistakes

  • Running two independent DPs, one per robot. The paths interact through shared cells, so they must be solved jointly.
  • Counting a cell twice when both robots stand on it.
  • Initializing unreachable states to 0 instead of -1, which lets robots appear to start from columns they could not have reached.
  • Forgetting to bounds check the predecessor columns, which reads outside the grid at the edges.

Frequently asked questions

Why can both robots be handled in one DP?

They move down in lockstep, so they always share a row. The pair of columns fully describes the state, which gives an n × n table per row.

How is Cherry Pickup II different from Cherry Pickup?

In the first problem a single person goes down and back up through obstacles, which is modeled as two people moving together with a step counter. Here both robots only move down, so the row index itself synchronizes them and there are no obstacles.

Do the robots ever need to cross each other?

Crossing never helps, since swapping the two paths at the crossing point gives the same cherries. The DP does not forbid it, but it does not need to, because the maximum is unaffected.