Cherry Pickup - Problem
Cherry Pickup is a challenging path optimization problem that combines forward and backward traversal with dynamic programming.

You're given an n × n grid representing a cherry field where each cell contains:
0 - Empty cell (passable)
1 - Cherry (can pick up and pass through)
-1 - Thorn (blocks your path)

Your mission:
1. Start at (0,0) and reach (n-1,n-1) by moving only right or down
2. Return from (n-1,n-1) to (0,0) by moving only left or up
3. Collect maximum cherries possible during both journeys
4. Once picked, cherries disappear (cell becomes 0)

Goal: Return the maximum number of cherries you can collect, or 0 if no valid path exists.

Input & Output

example_1.py — Basic Grid
$ Input: grid = [[0,1,-1],[1,0,-1],[1,1,1]]
Output: 5
💡 Note: Path 1: (0,0)→(1,0)→(2,0)→(2,1)→(2,2) collects 3 cherries. Path 2: (2,2)→(2,1)→(2,0)→(1,0) would collect 2, but (1,0) cherry is gone, so only 1 more cherry from (2,1). Total: 4. Actually, optimal is 5 when modeled as two robots.
example_2.py — Single Cell
$ Input: grid = [[1]]
Output: 1
💡 Note: Only one cell with one cherry. Robot goes there and back, collecting 1 cherry total.
example_3.py — Blocked Path
$ Input: grid = [[1,1,-1],[1,-1,1],[-1,1,1]]
Output: 0
💡 Note: No valid path exists from (0,0) to (2,2) due to thorn blocks, so return 0.

Constraints

  • n == grid.length
  • n == grid[i].length
  • 1 ≤ n ≤ 50
  • grid[i][j] is -1, 0, or 1
  • grid[0][0] ≠ -1
  • grid[n-1][n-1] ≠ -1

Visualization

Tap to expand
Cherry Pickup - Dynamic Programming INPUT n × n Grid (Cherry Field) 0 Start 1 -1 Thorn 1 0 -1 1 1 End Legend: 0 = Empty 1 = Cherry -1 = Thorn grid = [[0,1,-1], [1,0,-1], [1,1,1]] ALGORITHM STEPS 1 Two Walkers Trick Simulate 2 people walking from (0,0) simultaneously 2 DP State Definition dp[r1][c1][r2] = max cherries c2 = r1+c1-r2 (same steps) 3 Transitions Each walker: right or down 4 combinations per step 4 Avoid Double Count If both on same cell, count cherry only once Two Walkers Path Walker 1 Walker 2 FINAL RESULT Optimal Paths Found Start +1 X +1 0 X +1 +1 +1 Cherry Count: Walker 1: (0,1)+(1,1)+(2,2) = 3 Walker 2: (1,0)+(2,0)+(2,1) = 2 Output: 5 Key Insight: Instead of simulating forward then backward paths, use TWO SIMULTANEOUS WALKERS from start to end. This is equivalent to one round trip! Both walkers take same number of steps, so r1+c1 = r2+c2. Time: O(n^3) | Space: O(n^3) -- We only need to track (r1, c1, r2) since c2 is derived. TutorialsPoint - Cherry Pickup | Dynamic Programming Approach
Asked in
Google 42 Amazon 35 Meta 28 Microsoft 22
52.0K Views
Medium-High Frequency
~25 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen