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: Two Robots Approach🍒🍒🍒🍒🍒🍒🍒3D DP Formuladp[step][r1][r2] =max cherries after 'step' movesrobot1 at row r1, robot2 at row r2Transitions (4 combinations):• Both right: dp[step+1][r1][r2]• R1 right, R2 down: dp[step+1][r1][r2+1]• R1 down, R2 right: dp[step+1][r1+1][r2]• Both down: dp[step+1][r1+1][r2+1]🤖 Robot 1 (Teal) and Robot 2 (Orange) move independentlyColumn positions calculated as: c1 = step - r1, c2 = step - r2Time: O(n³) | Space: O(n³) → O(n²) optimized
Understanding the Visualization
1
Problem Transformation
Convert 'go down and come back up' into 'two robots go down together'
2
3D State Space
Track dp[steps][robot1_row][robot2_row] for all possible states
3
Movement Simulation
Each robot can move right or down, giving 4 possible combinations per step
4
Cherry Logic
If robots are at the same position, count cherry once; otherwise count both
Key Takeaway
🎯 Key Insight: Transform the problem from 'one robot round-trip' to 'two robots one-way journey' - this eliminates path dependencies and enables efficient dynamic programming!
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