Limited time: AI code review, hints, mock interviews, whiteboard analysis, and all Pro features are unlocked. Enroll

Cherry Pickup

Hard

Topics
ArrayDynamic ProgrammingMatrix

You are given an n x n grid where each cell is 0 (empty), 1 (a cherry), or -1 (a thorn you cannot pass).

Walk from (0, 0) to (n-1, n-1) moving only right or down, then walk back from (n-1, n-1) to (0, 0) moving only left or up. You pick up every cherry you step on, and that cell becomes empty.

Return the maximum number of cherries you can collect. If there is no valid round trip, return 0.

Example 1

Input:  grid = [[0,1,-1],[1,0,-1],[1,1,1]]
Output: 5
Explanation: Go down the left column and along the bottom row collecting 4 cherries, then return through the middle collecting 1 more.

Example 2

Input:  grid = [[1,1,-1],[1,-1,1],[-1,1,1]]
Output: 0
Explanation: The thorns block every round trip.

Constraints

  • n == grid.length == grid[i].length
  • 1 <= n <= 50
  • grid[i][j] is -1, 0, or 1
  • grid[0][0] != -1
  • grid[n-1][n-1] != -1
Run ⌘' · Submit ⌘⏎
SensAI SensAI
Beta
Listening...
Tap mic to stop voice mode

Unlock AI Features

One click to activate - no payment, no credit card. Just sign in and you're in.

AI code review and hints
SensAI chat assistant
AI mock interviews
Whiteboard analysis
100% free during early access