Cherry Pickup
Difficulty: Hard · Pattern: 2-D Dynamic Programming · LeetCode #741
grid[r][c] is 0 (empty), 1 (a cherry) or -1 (a thorn, impassable). Walk from (0,0) to (n−1,n−1) moving right/down, then back to (0,0) moving left/up, picking up the cherries you pass (each cell's cherry can be picked once). Return the maximum number of cherries, or 0 if no valid round trip exists.
Examples
text
[[0,1,-1],[1,0,-1],[1,1,1]] → 5
[[1,1,-1],[1,-1,1],[-1,1,1]] → 0Hints
- Taking the best path, removing its cherries and then taking the best second path is wrong. The greedy first path can block a better total.
- The return trip is just another forward trip. Model two people walking forward at the same time.
- After
tsteps each walker satisfiesr + c = t, so the state(t, r1, r2)determines both positions.
Approach
dp[r1][r2] at step t = the max cherries when walker A is at (r1, t−r1) and walker B at (r2, t−r2):
text
for t in 1..2n-2:
for r1, r2 (valid, not thorns):
best = max of dp_prev over (r1 or r1-1) × (r2 or r2-1)
gain = grid[r1][c1] + (grid[r2][c2] if (r1,c1) != (r2,c2) else 0)
dp[r1][r2] = best + gainCounting a shared cell once handles "each cherry picked once". Unreachable states stay −∞, and the answer is max(0, dp[n−1][n−1]). That's O(n³) time and O(n²) space. (Cherry Pickup II, LC 1463, is the same idea with two robots moving side by side.)
Complexity
Time: O(n³). Space: O(n²).
Python solution
def cherryPickup(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):
nd = [[NEG] * n for _ in range(n)]
for r1 in range(max(0, t - n + 1), min(n, t + 1)):
c1 = t - r1
if grid[r1][c1] == -1:
continue
for r2 in range(r1, min(n, t + 1)):
c2 = t - r2
if c2 < 0 or c2 >= n or grid[r2][c2] == -1:
continue
best = max(dp[r1][r2], dp[r1 - 1][r2] if r1 else NEG,
dp[r1][r2 - 1] if r2 else NEG, dp[r1 - 1][r2 - 1] if r1 and r2 else NEG)
if best == NEG:
continue
gain = grid[r1][c1] + (grid[r2][c2] if r1 != r2 else 0)
nd[r1][r2] = best + gain
dp = nd
return max(0, dp[n - 1][n - 1])JavaScript solution
function cherryPickup(grid) {
const n = grid.length, NEG = -Infinity;
let dp = Array.from({ length: n }, () => new Array(n).fill(NEG));
dp[0][0] = grid[0][0];
for (let t = 1; t <= 2 * n - 2; t++) {
const nd = Array.from({ length: n }, () => new Array(n).fill(NEG));
for (let r1 = Math.max(0, t - n + 1); r1 <= Math.min(n - 1, t); r1++) {
const c1 = t - r1;
if (grid[r1][c1] === -1) continue;
for (let r2 = r1; r2 <= Math.min(n - 1, t); r2++) {
const c2 = t - r2;
if (c2 < 0 || c2 >= n || grid[r2][c2] === -1) continue;
let best = dp[r1][r2];
if (r1) best = Math.max(best, dp[r1 - 1][r2]);
if (r2) best = Math.max(best, dp[r1][r2 - 1]);
if (r1 && r2) best = Math.max(best, dp[r1 - 1][r2 - 1]);
if (best === NEG) continue;
nd[r1][r2] = best + grid[r1][c1] + (r1 !== r2 ? grid[r2][c2] : 0);
}
}
dp = nd;
}
return Math.max(0, dp[n - 1][n - 1]);
}