
Problem
Solution
Submissions
Cherry Pickup
Certification: Advanced Level
Accuracy: 0%
Submissions: 0
Points: 15
Write a C program to find the maximum number of cherries you can collect in a grid. You start at the top-left corner (0,0) and need to reach the bottom-right corner (n-1,n-1), then return back to the top-left corner. You can only move right or down when going to the bottom-right, and only move left or up when returning. Each cell contains a number of cherries (0 or positive integer), and once you pick cherries from a cell, it becomes 0.
Example 1
- Input: grid = [[0,1,1,1],[1,0,1,1],[1,1,1,1],[1,1,0,0]]
- Output: 5
- Explanation:
- Path to bottom-right: (0,0) → (0,1) → (0,2) → (1,2) → (2,2) → (3,2) → (3,3) collecting 4 cherries.
- Path back to top-left: (3,3) → (2,3) → (1,3) → (0,3) → (0,2) → (0,1) → (0,0) collecting 1 more cherry.
- Total cherries collected = 5.
- Path to bottom-right: (0,0) → (0,1) → (0,2) → (1,2) → (2,2) → (3,2) → (3,3) collecting 4 cherries.
Example 2
- Input: grid = [[1,1,1,1,0,0,0],[0,0,0,1,0,0,0],[0,0,0,1,0,0,1],[1,0,0,1,0,0,0],[0,0,0,1,0,0,0],[0,0,0,1,0,0,0],[0,0,0,1,1,1,1]]
- Output: 15
- Explanation:
- The optimal path collects cherries strategically on both forward and return journeys.
- Maximum cherries that can be collected is 15.
- This requires dynamic programming to find the optimal solution.
- The optimal path collects cherries strategically on both forward and return journeys.
Constraints
- 1 ≤ grid.length ≤ 50
- 1 ≤ grid[i].length ≤ 50
- 0 ≤ grid[i][j] ≤ 100
- Time Complexity: O(n³)
- Space Complexity: O(n³)
Editorial
My Submissions
All Solutions
Lang | Status | Date | Code |
---|---|---|---|
You do not have any submissions for this problem. |
User | Lang | Status | Date | Code |
---|---|---|---|---|
No submissions found. |
Solution Hints
- Think of this as two people walking simultaneously from top-left to bottom-right
- Use 3D dynamic programming with states (i1, j1, i2) where j2 = i1 + j1 - i2
- At each step, both people can move right or down
- If both people are at the same cell, count cherries only once
- Use memoization to avoid recalculating subproblems
- The base case is when both reach the bottom-right corner