HardArrayDynamic ProgrammingMatrix

Cherry Pickup

LeetCode
1 approach, code in all languages

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.length
  • n == grid[i].length
  • 1 <= n <= 50
  • grid[i][j] is -1, 0, or 1
  • grid[0][0] != -1 and grid[n - 1][n - 1] != -1
You've got the patterns

Patterns get you through the screen. Shipping gets you hired.

FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.

750+ engineers trained · frontend, backend, AWS & AI

August 15 · 0d left
Enroll Now