You are given an grid with cherries (1), empty spaces (0), and thorns (-1). You start at (0, 0), move to (n-1, n-1) picking up cherries, and then return to (0, 0) picking up more. Thorns are impassable. Once a cherry is picked, the cell becomes empty. The goal is to maximize the total number of cherries collected.
This is a classic "Hard" Dynamic Programming problem asked by nearly every top-tier company (Google, Amazon, Meta). It tests your ability to transform a two-pass problem into a single-pass problem. You can't just find the best path forward and then the best path back (that's a greedy error); you must simulate two people moving from (0,0) to (n-1, n-1) simultaneously.
The pattern is Dynamic Programming on a Matrix with simultaneous paths. We track the state , where is the number of steps taken (time), is the row of the first person, and is the row of the second person. The columns can be derived as and . At each step, if both people are at the same cell, you only count the cherry once.
Grid: 1 1 1 0 0 0 0 0 1
The most common mistake is the "Greedy" approach: find the max path from A to B, remove those cherries, then find the max path from B to A. This doesn't work because the "best" first path might leave the second path with very few options. Another mistake is using a 4D DP state , which is and might time out, whereas is sufficient.
Whenever a problem involves a "round trip" in a grid, try to reframe it as two people moving from the start to the end at the same time. This is a recurring pattern in path optimization problems.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Dungeon Game | Hard | Solve | |
| Cherry Pickup II | Hard | Solve | |
| Minimum Falling Path Sum II | Hard | Solve | |
| Maximum Vacation Days | Hard | Solve | |
| Check if There Is a Valid Parentheses String Path | Hard | Solve |