06. Cherry Pickup II (3D Grid DP)

Difficulty:HardPattern:3D Grid DPTime:O(R * C^2)Space:O(R * C^2)

You are given a rows x cols matrix grid. You have two robots: Robot 1 starts at (0, 0) and Robot 2 starts at (0, cols - 1). Return the maximum cherries collected by both robots.

How It Works & Algorithmic Design

Solves using 3D Simultaneous Grid Dynamic Programming:

  1. DP State: Let dp[r][c1][c2] be max cherries collected at row $r$ with Robot 1 at column $c_1$ and Robot 2 at column $c_2$.
  2. Grid Cherry Addition:
    • If $c_1 === c_2$, cherries gained = grid[r][c1].
    • Else, cherries gained = grid[r][c1] + grid[r][c2].
  3. Transition: For each candidate column move $(dc_1, dc_2) \in {-1, 0, 1}^2$:
    • dp[r][c1][c2] = cherry + max(dp[r+1][c1+dc1][c2+dc2]).

Why This Approach Works Best

Saves $O(2^R)$ exponential path choices by moving both robots simultaneously down row $r$ in $O(R \cdot C^2)$ time.

Example Walkthrough

Input Grid

[[3,1,1],[2,5,1],[1,5,5],[2,1,1]]

4x3 grid.

Dual Paths

Robot 1 moves (0,0)->(1,1)->(2,1)->(3,0). Robot 2 moves (0,2)->(1,1)->(2,2)->(3,2).

Optimized cherry collection paths.

Output

24

Max total cherries.

Answer: Cherry Pickup II 3D DP implementation

function cherryPickup(grid) {
  const rows = grid.length, cols = grid[0].length;
  const memo = Map();
  function dfs(r, c1, c2) {
    if (c1 < 0 || c1 >= cols || c2 < 0 || c2 >= cols) return -Infinity;
    if (r === rows) return 0;
    const key = `${r},${c1},${c2}`;
    if (memo.has(key)) return memo.get(key);
    let cherries = c1 === c2 ? grid[r][c1] : grid[r][c1] + grid[r][c2];
    let maxNext = -Infinity;
    for (let d1 = -1; d1 <= 1; d1++) {
      for (let d2 = -1; d2 <= 1; d2++) {
        maxNext = Math.max(maxNext, dfs(r + 1, c1 + d1, c2 + d2));
      }
    }
    const res = cherries + maxNext;
    memo.set(key, res);
    return res;
  }
  return dfs(0, 0, cols - 1);
}

Advance both robots row by row, memoizing state using 3D dynamic programming grid.

Key Takeaways
  • Traversing both robots row by row simplifies state matching.

  • Handles cell overlaps using $c_1 === c_2$ check.

  • Runs in $O(R \cdot C^2)$ space and time.