AlgoMaster Logo

Cherry Pickup

Ashish

Ashish Pratap Singh

hard

Problem Description

Solve it on LeetCode

Approaches

1. Recursive Approach

The idea is to use a recursive approach, trying to solve the problem by walking from the top-left to the bottom-right and then back again. Since there are two distinct paths (forward and backward), the problem can be visualized like two people moving simultaneously across the grid.

Intuition:

  • You start at the top-left of the grid and try to reach the bottom-right corner.
  • Think of this problem as having two people start at (0, 0) and both try to end at (n-1, n-1).
  • The task is to collect the maximum number of cherries from the top left to the bottom right and back to the top left.

Pseudocode:

  1. Define a recursive function maxCherries(r1, c1, r2, c2) where r1, c1 are the row and column for the first person, and r2, c2 for the second person.
  2. If either of the two paths is out of the grid or hits a thorn, return a large negative number because it’s not a valid path.
  3. When we reach the bottom-right corner, return the value of the point (they add the cherry picked) except if it's the last point.
  4. Otherwise, try all possible moves for both persons, and accumulate the maximum cherries possible.

Code:

2. Dynamic Programming Approach

The recursive method will be inefficient for larger grids due to redundant calculations. Dynamic Programming (DP) allows us to break down the problem into smaller overlapping subproblems, caching results and reusing them.

Intuition:

  • We'll use a 3D DP array where dp[r1][c1][r2] represents the maximum number of cherries both persons can pick starting from cell (r1, c1) and (r2, c2) respectively to cell (n-1, n-1) and back.
  • The base case is reaching (n-1, n-1) where if both arrive together at this point, they can pick the cherries there only once.

Code:

3. Dynamic Programming with State Compression

In this enhanced variation, we reduce the space complexity further by understanding that only the immediate previous row states are needed to compute the current row state in a 2D traversal.

Intuition:

Use only a 2D DP array, reducing space complexity but altering our method to fit inline with computed states.

Code: