Cherry Pickup
Hard
Topics
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
-1 cells are thorns that block a route.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
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
- 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). - Use state
(t, r1, r2)wheretis the step count and the columns are recovered asc1 = t - r1andc2 = t - r2. Skip states whose columns fall outside the grid or land on a thorn. - 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. - Each walker independently moved down or right, so combine the four predecessors from step
t - 1and take the maximum. Propagate an "unreachable" sentinel so blocked states never contribute. - 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 == r2is 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 0import java.util.*;
class Solution {
public int cherryPickup(int[][] grid) {
int n = grid.length;
final int NEG = Integer.MIN_VALUE / 4;
int[][] best = new int[n][n];
for (int[] row : best) Arrays.fill(row, NEG);
best[0][0] = grid[0][0];
for (int step = 1; step <= 2 * n - 2; step++) {
int[][] next = new int[n][n];
for (int[] row : next) Arrays.fill(row, NEG);
for (int r1 = Math.min(step, n - 1); r1 >= 0; r1--) {
int c1 = step - r1;
if (c1 < 0 || c1 >= n || grid[r1][c1] == -1) continue;
for (int r2 = Math.min(step, n - 1); r2 >= 0; r2--) {
int c2 = step - r2;
if (c2 < 0 || c2 >= n || grid[r2][c2] == -1) continue;
int picked = (r1 == r2) ? grid[r1][c1] : grid[r1][c1] + grid[r2][c2];
int[] p1s = {r1, r1 - 1}, p2s = {r2, r2 - 1};
for (int p1 : p1s) {
for (int p2 : p2s) {
if (p1 < 0 || p2 < 0 || best[p1][p2] == NEG) continue;
next[r1][r2] = Math.max(next[r1][r2], best[p1][p2] + picked);
}
}
}
}
best = next;
}
int answer = best[n - 1][n - 1];
return answer == NEG ? 0 : Math.max(0, answer);
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: int cherryPickup(vector<vector<int>>& grid) {
int n = grid.size();
const int NEG = INT_MIN / 4;
vector<vector<int>> best(n, vector<int>(n, NEG));
best[0][0] = grid[0][0];
for (int step = 1; step <= 2 * n - 2; step++) {
vector<vector<int>> next(n, vector<int>(n, NEG));
for (int r1 = min(step, n - 1); r1 >= 0; r1--) {
int c1 = step - r1;
if (c1 < 0 || c1 >= n || grid[r1][c1] == -1) continue;
for (int r2 = min(step, n - 1); r2 >= 0; r2--) {
int c2 = step - r2;
if (c2 < 0 || c2 >= n || grid[r2][c2] == -1) continue;
int picked = (r1 == r2) ? grid[r1][c1] : grid[r1][c1] + grid[r2][c2];
int p1s[2] = {r1, r1 - 1}, p2s[2] = {r2, r2 - 1};
for (int x = 0; x < 2; x++) {
for (int y = 0; y < 2; y++) {
int p1 = p1s[x], p2 = p2s[y];
if (p1 < 0 || p2 < 0 || best[p1][p2] == NEG) continue;
next[r1][r2] = max(next[r1][r2], best[p1][p2] + picked);
}
}
}
}
best = next;
}
int answer = best[n - 1][n - 1];
return answer == NEG ? 0 : max(0, answer);
}
};/**
* @param {number[][]} grid
* @return {number}
*/ var cherryPickup = function(grid) {
const n = grid.length, NEG = -Infinity;
let best = Array.from({ length: n }, () => new Array(n).fill(NEG));
best[0][0] = grid[0][0];
for (let step = 1; step <= 2 * n - 2; step++) {
const next = Array.from({ length: n }, () => new Array(n).fill(NEG));
for (let r1 = Math.min(step, n - 1); r1 >= 0; r1--) {
const c1 = step - r1;
if (c1 < 0 || c1 >= n || grid[r1][c1] === -1) continue;
for (let r2 = Math.min(step, n - 1); r2 >= 0; r2--) {
const c2 = step - r2;
if (c2 < 0 || c2 >= n || grid[r2][c2] === -1) continue;
const picked = r1 === r2 ? grid[r1][c1] : grid[r1][c1] + grid[r2][c2];
for (const p1 of [r1, r1 - 1]) {
for (const p2 of [r2, r2 - 1]) {
if (p1 < 0 || p2 < 0 || best[p1][p2] === NEG) continue;
const cand = best[p1][p2] + picked;
if (cand > next[r1][r2]) next[r1][r2] = cand;
}
}
}
}
best = next;
}
const answer = best[n - 1][n - 1];
return answer === NEG ? 0 : Math.max(0, answer);
};