Cherry Pickup II

Hard Dynamic Programming 2D DP

Cherry Pickup II is a hard dynamic programming problem solved with the 2d dp pattern. The best approach, optimal (bottom-up dp, one row at a time), runs in O(rows * cols^2) time and O(cols^2) space. Below are 3 approaches in Java, Python, C++ and JavaScript, from brute force (recursion over both robots) up.

Problem

You are given a rows × cols grid of non-negative integers, where grid[i][j] is the number of cherries in that cell.

Two robots collect cherries. The first starts in the top-left cell (0, 0) and the second in the top-right cell (0, cols - 1).

At every step both robots move down one row at the same time. From (i, j) a robot may move to (i + 1, j - 1), (i + 1, j) or (i + 1, j + 1), and it must stay inside the grid. A robot picks up all cherries in every cell it visits, including its starting cell, and a picked cell becomes empty.

If both robots stand on the same cell, its cherries are collected only once. The walk ends when both robots reach the bottom row.

Return the largest total number of cherries the two robots can collect together.

Examples

Example 1

Input
grid = [[2,0,3],[1,4,1],[5,1,2],[0,3,0]]
Output
20
Why
The left robot goes down columns 0, 1, 0, 1 and picks 2 + 4 + 5 + 3 = 14. The right robot stays in column 2 and picks 3 + 1 + 2 + 0 = 6. Together that is 20, and no pair of routes does better.

Example 2

Input
grid = [[1,1],[1,1]]
Output
4
Why
Each robot stays in its own column, so all four cells are picked: 1 + 1 + 1 + 1 = 4.

Example 3

Input
grid = [[0,0,0],[0,9,1],[0,0,0]]
Output
10
Why
Both robots can reach the 9 in row 1, but if they both step onto it, it is counted only once and they end with 9. It is better for the left robot to take the 9 and the right robot to take the 1 next to it, for 10.

Constraints

  • rows == grid.length, cols == grid[i].length
  • 2 <= rows, cols <= 70
  • 0 <= grid[i][j] <= 100

Solve it here

Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.

00:00
Testcase

Run checks the testcases above (3 examples, or your own). Submit also runs 15 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.

Animated walkthrough

A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

Solutions

Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.

ApproachTimeSpace
Brute force (recursion over both robots)O(9^rows)O(rows)
Memoized recursion (top-down DP)O(rows * cols^2)O(rows * cols^2)
Optimal (bottom-up DP, one row at a time)O(rows * cols^2)O(cols^2)

1Brute force (recursion over both robots)

TimeO(9^rows)Every call branches into nine calls for the next row, and the recursion is rows levels deep.
SpaceO(rows)The call stack holds one frame per row.

Move the two robots together, one row at a time. In each row, collect the cherries under both robots (once if they share a cell), then try all nine ways the pair can step down and keep the best. A move off the grid is worth minus infinity, so it is never chosen.

  1. solve(r, c1, c2) is the most cherries from row r to the bottom, with the robots in columns c1 and c2.
  2. If c1 or c2 is outside the grid, return minus infinity.
  3. here = grid[r][c1], plus grid[r][c2] if c2 is a different column.
  4. On the last row, return here. Otherwise return here plus the best of solve(r + 1, c1 + d1, c2 + d2) over d1, d2 in {-1, 0, 1}.
  5. The answer is solve(0, 0, cols - 1).
class Solution {
    public int cherryPickup(int[][] grid) {
        return solve(grid, 0, 0, grid[0].length - 1);
    }

    // most cherries from row r down, robots in columns c1 and c2
    private int solve(int[][] grid, int r, int c1, int c2) {
        int cols = grid[0].length;
        if (c1 < 0 || c1 >= cols || c2 < 0 || c2 >= cols) return Integer.MIN_VALUE;
        int here = grid[r][c1];
        if (c1 != c2) here += grid[r][c2];
        if (r == grid.length - 1) return here;
        int best = Integer.MIN_VALUE;
        for (int d1 = -1; d1 <= 1; d1++) {
            for (int d2 = -1; d2 <= 1; d2++) {
                best = Math.max(best, solve(grid, r + 1, c1 + d1, c2 + d2));
            }
        }
        return here + best;
    }
}

2Memoized recursion (top-down DP)

TimeO(rows * cols^2)There are rows × cols × cols states, and each one tries nine moves once.
SpaceO(rows * cols^2)The memo has one entry per state; the call stack adds only rows frames.

The plain recursion reaches the same (row, c1, c2) along many different routes, and the answer from that point down never depends on how the robots got there. Store each answer in a three-dimensional memo the first time it is computed, and return it straight away after that.

  1. memo[r][c1][c2] starts at -1, meaning not computed. Every real answer is at least 0, so -1 is a safe marker.
  2. In solve, after the bounds check, return memo[r][c1][c2] if it is set.
  3. Otherwise compute the answer exactly as before, store it, and return it.
class Solution {
    private int[][][] memo;

    public int cherryPickup(int[][] grid) {
        int rows = grid.length, cols = grid[0].length;
        memo = new int[rows][cols][cols];
        for (int[][] layer : memo)
            for (int[] row : layer) Arrays.fill(row, -1);
        return solve(grid, 0, 0, cols - 1);
    }

    private int solve(int[][] grid, int r, int c1, int c2) {
        int cols = grid[0].length;
        if (c1 < 0 || c1 >= cols || c2 < 0 || c2 >= cols) return Integer.MIN_VALUE;
        if (memo[r][c1][c2] != -1) return memo[r][c1][c2];
        int here = grid[r][c1];
        if (c1 != c2) here += grid[r][c2];
        int best = 0;
        if (r < grid.length - 1) {
            best = Integer.MIN_VALUE;
            for (int d1 = -1; d1 <= 1; d1++) {
                for (int d2 = -1; d2 <= 1; d2++) {
                    best = Math.max(best, solve(grid, r + 1, c1 + d1, c2 + d2));
                }
            }
        }
        memo[r][c1][c2] = here + best;
        return memo[r][c1][c2];
    }
}

3Optimal (bottom-up DP, one row at a time)

TimeO(rows * cols^2)Each of the rows layers has cols × cols cells, and each cell checks nine neighbours.
SpaceO(cols^2)Only two cols × cols tables are alive at a time: the row below and the row being built.

Fill the answers from the bottom row up. For a fixed row, dp[c1][c2] is the most cherries from that row to the bottom when the robots stand in columns c1 and c2. A row only reads the row just below it, so keep a single cols by cols table for the row below and build a fresh one for the current row. Below the last row there is nothing left to pick, so the starting table is all zeros.

  1. dp is a cols × cols table of zeros: the empty row under the grid.
  2. For r from the last row up to row 0, build next: for every pair (c1, c2), best is the largest dp[n1][n2] over the nine moves that stay inside the grid.
  3. next[c1][c2] = grid[r][c1] (+ grid[r][c2] if c2 != c1) + best. Then dp = next.
  4. After row 0, both robots start in columns 0 and cols - 1, so return dp[0][cols - 1].
class Solution {
    public int cherryPickup(int[][] grid) {
        int rows = grid.length, cols = grid[0].length;
        // dp[c1][c2] = most cherries from the row below down, robots in columns c1 and c2
        int[][] dp = new int[cols][cols];
        for (int r = rows - 1; r >= 0; r--) {
            int[][] next = new int[cols][cols];
            for (int c1 = 0; c1 < cols; c1++) {
                for (int c2 = 0; c2 < cols; c2++) {
                    int best = 0;
                    for (int d1 = -1; d1 <= 1; d1++) {
                        for (int d2 = -1; d2 <= 1; d2++) {
                            int n1 = c1 + d1, n2 = c2 + d2;
                            if (n1 >= 0 && n1 < cols && n2 >= 0 && n2 < cols) {
                                best = Math.max(best, dp[n1][n2]);
                            }
                        }
                    }
                    int here = grid[r][c1];
                    if (c1 != c2) here += grid[r][c2];
                    next[c1][c2] = here + best;
                }
            }
            dp = next;
        }
        return dp[0][cols - 1];
    }
}

Edge cases to test

  • Only two columns: the robots can still meet in one column, but staying apart is never worse
  • Both robots land on the same cell: its cherries count once, not twice
  • A grid of all zeros: the answer is 0
  • The best cells are all in the middle columns, so the robots must walk toward each other
  • A robot moving off the left or right edge is not a legal move
  • Greedy fails: taking the most cherries in the next row can steer a robot away from a much bigger prize further down

Hints

Hint 1

Both robots move down one row at every step, so they are always in the same row. The state is just (row, column of robot 1, column of robot 2).

Hint 2

From one state there are 3 × 3 = 9 next states: each robot moves down-left, down or down-right. Add the cherries of the current row, counting a shared cell once.

Hint 3

Let dp[c1][c2] be the most cherries from the current row down to the bottom. Fill it from the last row up to the first; each row only needs the row below it. The answer is dp[0][cols - 1] for row 0.

FAQ

What is the best time complexity for Cherry Pickup II?

Optimal (bottom-up DP, one row at a time) runs in O(rows * cols^2) time and O(cols^2) extra space. Each of the rows layers has cols × cols cells, and each cell checks nine neighbours.

Which pattern does Cherry Pickup II use?

It is a dynamic programming problem that uses the 2d dp pattern. Other problems with the same pattern: Minimum Path Sum, Unique Paths, Unique Paths II.

Is there a brute force solution for Cherry Pickup II?

Yes. Brute force (recursion over both robots) takes O(9^rows) time and O(rows) space. Move the two robots together, one row at a time.

Which edge cases should I test for Cherry Pickup II?

Only two columns: the robots can still meet in one column, but staying apart is never worse; Both robots land on the same cell: its cherries count once, not twice; A grid of all zeros: the answer is 0; The best cells are all in the middle columns, so the robots must walk toward each other; A robot moving off the left or right edge is not a legal move; Greedy fails: taking the most cherries in the next row can steer a robot away from a much bigger prize further down.