Advertisement

Cherry Pickup - LeetCode 741 Solution

Cherry Pickup - Complete Solution Guide

Cherry Pickup is LeetCode problem 741, a Hard level challenge. This complete guide provides step-by-step explanations, multiple solution approaches, and optimized code in python3, java, cpp, c.

Problem Statement

You are given an n x n grid representing a field of cherries, each cell is one of three possible integers. 0 means the cell is empty, so you can pass through, 1 means the cell contains a cherry that you can pick up and pass through, or -1 means the cell contains a thorn that blocks your way. Return the maximum number of cherries you can collect by following the rules below : Starting at the position (0, 0) and reaching (n - 1, n - 1) by moving right or down through valid path cells (cells with v

Detailed Explanation

The Cherry Pickup problem presents an n x n grid representing a field of cherries. Each cell can be empty (0), contain a cherry (1), or be blocked by a thorn (-1). The goal is to find the maximum number of cherries that can be collected by starting at the top-left corner (0, 0), moving only right or down to reach the bottom-right corner (n-1, n-1), and then returning to (0, 0) by moving only left or up. When a cherry is picked, the cell becomes empty (0). If no valid path exists, the output should be 0. The key is to maximize cherry collection during both forward and backward paths.

Solution Approach

The provided solutions use a dynamic programming approach. Instead of thinking about two separate trips (forward and backward), the problem is reframed as two people starting at (0, 0) and moving simultaneously towards (n-1, n-1). `dp[r1][r2]` stores the maximum cherries collected when the first person is at row `r1` and the second person is at row `r2` after `k` steps (where k = r1 + c1 = r2 + c2). The code iterates through all possible values of `k` from 1 to `2n - 2`. For each `k`, it considers all possible row positions `r1` and `r2` for the two people. It calculates the corresponding column positions `c1` and `c2` based on `k`. The code then checks if these positions are valid (within the grid bounds and not blocked by a thorn). The value of `dp[r1][r2]` is updated based on the maximum cherries collected from the previous steps (up, left, up-left), plus the cherries picked up at the current positions. If both people are at the same location, the cherry is only counted once. The final result is stored in `dp[n-1][n-1]` after `2n-2` steps.

Step-by-Step Algorithm

  1. Step 1: Initialize a 2D DP table `dp` of size n x n, where `dp[i][j]` represents the maximum number of cherries that can be collected when the first person is at row `i` and the second person is at row `j` after `k` steps.
  2. Step 2: Set the base case: `dp[0][0] = grid[0][0]`. This means that initially, both people are at (0, 0) and have collected the cherry (if any) at that location.
  3. Step 3: Iterate through all possible values of `k` from 1 to `2 * n - 1`. This represents the number of steps taken by both people.
  4. Step 4: For each value of `k`, iterate through all possible row positions `r1` and `r2` for the two people.
  5. Step 5: Calculate the corresponding column positions `c1` and `c2` based on the equations `c1 = k - r1` and `c2 = k - r2`.
  6. Step 6: Check if the positions (r1, c1) and (r2, c2) are valid: within the grid bounds, not blocked by a thorn (-1).
  7. Step 7: If the positions are valid, calculate the maximum number of cherries collected from the previous steps by considering all possible combinations of previous row positions: `dp[r1][r2]`, `dp[r1 - 1][r2]`, `dp[r1][r2 - 1]`, and `dp[r1 - 1][r2 - 1]`. The maximum of these becomes `prev_cherries`.
  8. Step 8: Add the cherries picked up at the current positions (r1, c1) and (r2, c2) to `prev_cherries`. If `r1 == r2`, only add the cherry once; otherwise, add both.
  9. Step 9: Update `dp_next[r1][r2]` with the calculated value ( `prev_cherries` + cherries at current position ).
  10. Step 10: After processing all possible row positions for the current value of `k`, update the `dp` table with the `dp_next` table.
  11. Step 11: Finally, return `max(0, dp[n - 1][n - 1])`. This returns the maximum number of cherries collected, or 0 if no valid path exists.

Key Insights

  • Insight 1: Two paths can be considered as two people walking from (0,0) at the same time. This is crucial because we need to account for picking the same cherry twice if we simply do two independent pathfinding attempts.
  • Insight 2: Dynamic programming is suitable because the optimal solution depends on the optimal solutions of subproblems (i.e., the maximum cherries collected up to a certain point).
  • Insight 3: The problem can be simplified by considering two people moving from (0,0) to (n-1, n-1) simultaneously, as the time taken for the first person to go from (0,0) to (n-1, n-1) and the second person from (n-1, n-1) to (0,0) is equivalent to them both going from (0,0) to (n-1,n-1) since they are simply the reverse path.

Complexity Analysis

Time Complexity: O(n^3)

Space Complexity: O(n^2)

Topics

This problem involves: Array, Dynamic Programming, Matrix.

Companies

Asked at: Akuna Capital, Atlassian, Cisco, Flipkart, J.P. Morgan, Snowflake, Zomato.