Cherry Pickup - Problem
Cherry Pickup is a challenging path optimization problem that combines forward and backward traversal with dynamic programming.
You're given an
•
•
•
Your mission:
1. Start at
2. Return from
3. Collect maximum cherries possible during both journeys
4. Once picked, cherries disappear (cell becomes
Goal: Return the maximum number of cherries you can collect, or
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 down2. Return from
(n-1,n-1) to (0,0) by moving only left or up3. 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
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!
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code