Cherry Pickup
Implement cherryPickup
Given a square grid where each cell is blocked, empty, or holds one cherry, imagine making two trips from the top-left corner to the bottom-right corner, each only moving right or down. Find the maximum total number of cherries collectible across both trips combined — a cell visited by both trips only counts once — or 0 if no such pair of trips is possible at all.
Since both trips always take the same number of steps to have moved the same distance, their positions at any point can be tracked by row alone (the column follows from the step count), which keeps the state small enough to work with directly: track, after each step, the best total collectible so far for every pair of rows the two trips could be on. Starting both trips together at the top-left corner and sweeping forward one step at a time — where each trip independently either moves down or moves right — lets every later step be resolved using totals already computed for the step before it, skipping any pair of positions that would land on a blocked cell. Once both trips reach the bottom-right corner, that entry holds the answer.
Example 1:
Input: grid = [[1,1,1],[1,-1,1],[1,1,1]]
Output: 8
Example 2:
Input: grid = [[1,0],[0,1]]
Output: 2
Example 3:
Input: grid = [[1]]
Output: 1
+ 7 hidden test cases run on Submit.
Constraints:
- ●
1 ≤ grid.length ≤ 15 (a square n×n grid) - ●
grid[i][j] is -1 (blocked), 0 (empty), or 1 (one cherry) - ●
grid[0][0] and grid[n-1][n-1] are never -1
grid =
[[1,1,1], [1,-1,1], [1,1,1]]