Cherry Pickup
1 approach, code in every language
Problem description
You are given an n x n grid. Each cell holds 0 (empty), 1 (one cherry), or -1 (a thorn that blocks the path). Starting at the top-left cell (0, 0), you walk to the bottom-right cell (n - 1, n - 1) moving only right or down, and then walk back to (0, 0) moving only left or up.
Along the way you collect every cherry you pass over, and once a cherry is picked the cell becomes empty. You may never step on a thorn. Return the maximum number of cherries you can collect over the round trip; if there is no valid path that reaches the bottom-right corner and returns, the answer is 0.
Example 1
Input: grid = [[0,1,-1],[1,0,-1],[1,1,1]]
Output: 5
One optimal round trip collects cherries on the way down through the left and bottom cells and picks up the remaining ones on the way back, gathering 5 in total while avoiding both thorns.
Example 2
Input: grid = [[1,1,-1],[1,-1,1],[-1,1,1]]
Output: 0
The thorns split the grid so that no path can reach the bottom-right corner, so no valid round trip exists and the answer is 0.
Constraints
n == grid.lengthn == grid[i].length1 <= n <= 50grid[i][j] is -1, 0, or 1grid[0][0] != -1 and grid[n - 1][n - 1] != -1
Create a free account to see the solution
You get the step-by-step animation, the intuition and clean code in every language. Free, no credit card.
After the pattern
Now solve one you haven't seen.
Round Trip Parcel Pickup is our own problem on the technique behind Cherry Pickup: a new statement, so there's no answer to remember. Write it in your browser and run it against graded tests.
1,194 problems · 15,062 graded tests · free