Tutorialspoint
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.
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.
Constraints
  • 1 ≤ grid.length ≤ 50
  • 1 ≤ grid[i].length ≤ 50
  • 0 ≤ grid[i][j] ≤ 100
  • Time Complexity: O(n³)
  • Space Complexity: O(n³)
ArraysDynamic Programming EYLTIMindtree
Editorial

Login to view the detailed solution and explanation for this problem.

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.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

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

Steps to solve by this approach:

 Step 1: Initialize a 3D memoization array to store computed results for subproblems
 Step 2: Model the problem as two people walking simultaneously from (0,0) to (n-1,n-1)
 Step 3: Use coordinates (i1,j1) for person 1 and (i2,j2) for person 2, where j2 = i1+j1-i2
 Step 4: At each position, add cherries from both positions (count once if same position)
 Step 5: Try all four possible combinations of moves (down/right for each person)
 Step 6: Use memoization to avoid recalculating the same subproblems
 Step 7: Return the maximum cherries collected, or 0 if no valid path exists

Submitted Code :