You get an n × n field, grid. A cell holding 1 has a cherry, a cell holding 0 is empty, and a cell holding −1 is a thorn bush you cannot walk through.
Walk from the top-left cell to the bottom-right cell moving only right or down, then walk back to the top-left moving only left or up. Every cherry on a cell you step on is picked, and a picked cell becomes empty. Return the most cherries you can pick on the round trip, or 0 if there is no way to reach the bottom-right cell.
Example 1
Input: grid = [[0, 1, 1], [1, -1, 0], [1, 1, 0]] Output: 5 Why: go along the top and right, come back along the bottom and left
2 more examples and the constraints
Example 2
Input: grid = [[1, -1], [-1, 1]] Output: 0 Why: thorns block every way to the bottom-right cell
Example 3
Input: grid = [[1]] Output: 1 Why: start and end are the same cell
Constraints
- 1 ≤ n ≤ 50
- Each cell is −1, 0 or 1
- The top-left and bottom-right cells are never thorns
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Two walkers, memoizedO(n³)
- Step-by-step tableO(n³)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for a 50 × 50 field | Verdict |
|---|---|---|---|
| Two walkers, memoized | O(n³) | Clear; n³ memory | |
| Step-by-step table | O(n³) | Best; n² memory, no recursion |
n = side length of the grid.
Edge cases to test
- No way through. [[1, -1], [-1, 1]] gives 0, not the cherry at the start.
- One cell. [[1]] gives 1; there and back is the same single cell.
- Shared cells. When both walkers stand on one cell, count its cherry once.
- Greedy trips fail. Taking the best single path first can strand cherries the second trip could have reached.
- Field full of cherries. On a 50 × 50 field of 1s, two paths of 99 cells share only the two corners: 196.
Common mistakes
- Running the best path twice, which is not optimal.
- Counting a cherry twice when both walkers stand on the same cell.
- Returning −1 or a negative sentinel when the corner cannot be reached, instead of 0.
How to talk through it
- 1Clarify. Moves only right/down then left/up? Do picked cells become empty? What if the corner is unreachable?
- 2Show why greedy fails. Best path then best path again can miss cherries; the two trips must be planned together.
- 3Reframe the return. The way back reversed is a second way down. Move two walkers in step: state (t, r1, r2).
- 4Code the layers. Each state reads four earlier ones; add both cells, once if they match; keep two layers.
- 5Test out loud. Run the blocked field and the single cell before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?