Cherry Pickup

Hard

Topics
ArrayDynamic ProgrammingMatrix

You are given an n x n grid where each cell is 0 (empty), 1 (a cherry), or -1 (a thorn you cannot pass).

Walk from (0, 0) to (n-1, n-1) moving only right or down, then walk back from (n-1, n-1) to (0, 0) moving only left or up. You pick up every cherry you step on, and that cell becomes empty.

Return the maximum number of cherries you can collect. If there is no valid round trip, return 0.

Example 1

001-1110-12111012
startturnaround
You walk down-right to the far corner and then back up-left, and a cherry can only be taken once. Rather than two separate trips, the standard reading is two walkers moving down-right at the same time — same total, and a state of (step, row1, row2) instead of a path history. -1 cells are thorns that block a route.
2D grid — one row per line.
Input:  grid = [[0,1,-1],[1,0,-1],[1,1,1]]
Output: 5
Explanation: Go down the left column and along the bottom row collecting 4 cherries, then return through the middle collecting 1 more.

Example 2

011-111-112-111012
startturnaround
Input:  grid = [[1,1,-1],[1,-1,1],[-1,1,1]]
Output: 0
Explanation: The thorns block every round trip.

Constraints

  • n == grid.length == grid[i].length
  • 1 <= n <= 50
  • grid[i][j] is -1, 0, or 1
  • grid[0][0] != -1
  • grid[n-1][n-1] != -1
Editorial — intuition, approach, complexity and pitfalls

Intuition

The trip back, reversed, is just another top-left to bottom-right walk. So instead of one path out and one path home, model two people walking down simultaneously from the origin. Both take the same number of steps, so after t moves each sits on the anti-diagonal row + col == t — that shared step count is what collapses four coordinates into three and makes the state space polynomial.

Approach

  1. Reframe the round trip as two walkers leaving (0, 0) together, each moving only right or down, and both arriving at (n-1, n-1).
  2. Use state (t, r1, r2) where t is the step count and the columns are recovered as c1 = t - r1 and c2 = t - r2. Skip states whose columns fall outside the grid or land on a thorn.
  3. The value collected at a state is grid[r1][c1] + grid[r2][c2], except when both walkers are on the same cell — then count it once, since the cherry is already gone.
  4. Each walker independently moved down or right, so combine the four predecessors from step t - 1 and take the maximum. Propagate an "unreachable" sentinel so blocked states never contribute.
  5. The answer is the value at t = 2n - 2, r1 = r2 = n - 1, clamped to 0 when that state is unreachable.
class Solution:
    def cherryPickup(self, grid):
        n = len(grid)
        NEG = float("-inf")
        dp = [[NEG] * n for _ in range(n)]
        dp[0][0] = grid[0][0]
        for t in range(1, 2 * n - 1):
            nxt = [[NEG] * n for _ in range(n)]
            for r1 in range(min(t, n - 1), max(-1, t - n), -1):
                for r2 in range(min(t, n - 1), max(-1, t - n), -1):
                    c1, c2 = t - r1, t - r2
                    if grid[r1][c1] == -1 or grid[r2][c2] == -1:
                        continue
                    best = NEG
                    for p1 in (r1, r1 - 1):
                        for p2 in (r2, r2 - 1):
                            if p1 >= 0 and p2 >= 0 and dp[p1][p2] != NEG:
                                best = max(best, dp[p1][p2])
                    if best == NEG:
                        continue
                    gain = grid[r1][c1]
                    if r1 != r2:
                        gain += grid[r2][c2]
                    nxt[r1][r2] = best + gain
            dp = nxt
        return max(0, dp[n - 1][n - 1])

Dry Run

grid = 0  1 -1
       1  0 -1
       1  1  1
One trip down-and-right plus the trip back is the same as TWO trips down-and-right.
Run them in lockstep, one diagonal per step, so a walker on row r sits at column
step-r and the state collapses to just (r1, r2).
best[r1][r2] = most cherries with both walkers on the current diagonal.
step 0  best[0][0] = grid[0][0] = 0
step 1  r1=1 r2=1  both on (1,0)         picked 1 -- counted once   best[1][1] = 1
        r1=1 r2=0  (1,0) and (0,1)       picked 1+1 = 2             best[1][0] = 2
        r1=0 r2=1  the mirror image      picked 2                   best[0][1] = 2
        r1=0 r2=0  both on (0,1)         picked 1                   best[0][0] = 1
step 2  r1=2 r2=1  (2,0) and (1,1)  picked 1+0 = 1  from best[1][0]=2   best[2][1] = 3
        r1=1 r2=2  the mirror image                                     best[1][2] = 3
        r1=2 r2=2  both on (2,0)   picked 1        from best[1][1]=1    best[2][2] = 2
        r1=1 r2=1  both on (1,1)   picked 0        from best[1][0]=2    best[1][1] = 2
        column 2 is -1 on rows 0 and 1, so every pair that needs it is skipped
step 3  r1=2 r2=2  both on (2,1)   picked 1        from best[2][1]=3    best[2][2] = 4
        that is the only surviving entry: the -1 wall has forced both trips
        through (2,0) and (2,1)
step 4  r1=2 r2=2  both on (2,2)   picked 1        from best[2][2]=4    best[2][2] = 5
answer best[2][2] = 5
The one-line double-count guard is the whole correctness argument:
    picked = grid[r1][c1] if r1 == r2 else grid[r1][c1] + grid[r2][c2]
Because the walkers advance in lockstep they can only ever meet by standing on the
same cell, and there the cherry must count once. Drop the r1 == r2 branch and this
grid returns 8 instead of 5.
Greedily taking the best single path and then re-running on what is left is NOT
equivalent. On grid [[0,0,1],[1,1,1],[0,1,0]] the greedy first trip swallows the
whole middle row for 3, leaving only 1 for the second trip -- total 4, while the
lockstep DP splits that row between the two trips and gets 5.

Complexity

  • Time — O(n^3) — 2n step layers times n^2 row pairs, with constant work each.
  • Space — O(n^2) — only the previous step layer is needed.

Common Pitfalls

  • Running two independent greedy or DP passes and adding them is wrong. The first path removes cherries the second one would have taken, and no single-path optimum accounts for that.
  • Double-counting the shared cell when r1 == r2 is the most common bug and inflates the answer.
  • An unreachable state must be a sentinel, not 0. Treating blocked states as zero lets paths teleport through thorns.
  • Return max(0, ...). A fully blocked grid has no round trip and must answer 0, not negative infinity.
  • Do the easier Cherry Pickup II first — there both walkers start on row 0, so the step index is the row and the state drops to two dimensions.

Full Solution — all languages

class Solution:
    def cherryPickup(self, grid):
        n = len(grid)
        NEG = float('-inf')
        best = [[NEG] * n for _ in range(n)]
        best[0][0] = grid[0][0]
        for step in range(1, 2 * n - 1):
            nxt = [[NEG] * n for _ in range(n)]
            for r1 in range(min(step, n - 1), -1, -1):
                c1 = step - r1
                if c1 < 0 or c1 >= n or grid[r1][c1] == -1:
                    continue
                for r2 in range(min(step, n - 1), -1, -1):
                    c2 = step - r2
                    if c2 < 0 or c2 >= n or grid[r2][c2] == -1:
                        continue
                    picked = grid[r1][c1] if r1 == r2 else grid[r1][c1] + grid[r2][c2]
                    for p1 in (r1, r1 - 1):
                        for p2 in (r2, r2 - 1):
                            if p1 < 0 or p2 < 0:
                                continue
                            if best[p1][p2] == NEG:
                                continue
                            cand = best[p1][p2] + picked
                            if cand > nxt[r1][r2]:
                                nxt[r1][r2] = cand
            best = nxt
        return max(0, best[n - 1][n - 1]) if best[n - 1][n - 1] != NEG else 0
Asked at PhonePe Uber
SensAI
Beta
Tap the mic to stop voice mode