Cherry Pickup II
Hard
Topics
Given a grid where each cell holds a number of cherries, two robots start at the top-left (0,0) and top-right (0, cols-1). Each robot moves down one row at a time to a diagonally-left, straight-down, or diagonally-right cell. When a robot passes a cell it collects its cherries; if both robots are on the same cell only one collection counts. Return the maximum cherries both robots can collect together after reaching the bottom row.
Example 1
Input: grid = [[3,1,1],[2,5,1],[1,5,5],[2,1,1]] Output: 24
Example 2
Input: grid = [[5]] Output: 5
Constraints
- 2 <= rows, cols <= 70
- 0 <= grid[i][j] <= 100
Editorial — intuition, approach, complexity and pitfalls
Intuition
Running the two robots one after the other does not work: the first robot's greedy path changes what is left for the second, and the best joint outcome often needs both to take individually worse paths. They have to move in lockstep so the state can see both at once.
Both robots advance exactly one row per step, which is the structural gift here — the row index is shared, so the state is (row, col of A, col of B) rather than two independent positions in time. From one state there are 3 × 3 = 9 moves. The only interaction is the same-cell rule: when both robots stand on one cell, its cherries count once.
Approach
- Define
solve(row, c1, c2)as the best total collectable from this row downward. - Return negative infinity if either column is off the grid, so illegal moves lose.
- Collect
grid[row][c1] + grid[row][c2], or just one of them whenc1 == c2. - On the last row, stop. Otherwise take the best of the 9 next-row combinations and add it.
- Memoise on the three-part state; the answer is
solve(0, 0, cols-1).
Dry Run
grid 3 1 1
2 5 1
1 5 5
2 1 1
optimal play, reconstructed from the memo table
row A col B col A takes B takes row total running
0 0 2 3 1 4 4
1 0 1 2 5 7 11
2 1 2 5 5 10 21
3 0 1 2 1 3 24
answer 24
note row 1: A stays in column 0 for only 2 cherries so that B can take the 5.
Greedily sending A to the 5 first would score 23.Complexity
- Time — O(rows · cols²): at the stated bound of 70 that is 343,000 states, each relaxing 9 transitions, so about 3.1 million operations. Measured at 0.22s for a 70×70 grid.
- Space — O(rows · cols²) for the memo. Because each row depends only on the next, a bottom-up version keeps two
cols × colslayers and is O(cols²) — worth offering as the follow-up.
Common Pitfalls
- Optimising the robots one at a time. The dry run above is the counterexample: the joint optimum requires robot A to take a worse cell in row 1.
- Double-counting the shared cell. When
c1 == c2only one robot collects. - Memoising on
(row, c1, c2)but allowingc1 > c2to be a distinct state from(row, c2, c1). It is correct, just twice the table; enforcingc1 <= c2halves it. - Returning 0 rather than negative infinity for an out-of-bounds column, which makes walking off the grid look free and inflates the answer.
- Assuming the robots must end in particular columns. They may finish anywhere on the bottom row.
- Letting the robots cross and treating that as illegal. Nothing forbids it; the same-cell rule is the only constraint on their relative position.
Full Solution — all languages
class Solution:
def cherryPickup(self, grid):
R = len(grid)
C = len(grid[0])
from functools import lru_cache
@lru_cache(maxsize=None)
def solve(r, c1, c2):
if c1 < 0 or c1 >= C or c2 < 0 or c2 >= C:
return float('-inf')
cur = grid[r][c1] + (grid[r][c2] if c1 != c2 else 0)
if r == R - 1:
return cur
best = float('-inf')
for d1 in (-1, 0, 1):
for d2 in (-1, 0, 1):
best = max(best, solve(r + 1, c1 + d1, c2 + d2))
return cur + best
return solve(0, 0, C - 1)import java.util.*;
class Solution {
public int cherryPickup(int[][] grid) {
this.g = grid;
this.R = grid.length;
this.C = grid[0].length;
this.memo = new Integer[R][C][C];
return solve(0, 0, C - 1);
}
int[][] g;
int R, C;
Integer[][][] memo;
private int solve(int r, int c1, int c2) {
if (c1 < 0 || c1 >= C || c2 < 0 || c2 >= C) return Integer.MIN_VALUE;
if (memo[r][c1][c2] != null) return memo[r][c1][c2];
int cur = g[r][c1] + (c1 != c2 ? g[r][c2] : 0);
if (r == R - 1) {
memo[r][c1][c2] = cur;
return cur;
}
int best = Integer.MIN_VALUE;
for (int d1 = -1; d1 <= 1; d1++) for (int d2 = -1; d2 <= 1; d2++) best = Math.max(best, solve(r + 1, c1 + d1, c2 + d2));
memo[r][c1][c2] = cur + best;
return cur + best;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: int cherryPickup(vector<vector<int>>& grid) {
int R = grid.size(), C = grid[0].size();
vector<vector<vector<int>>> memo(R, vector<vector<int>>(C, vector<int>(C, INT_MIN)));
function<int(int,int,int)> solve = [&](int r, int c1, int c2) -> int {
if (c1 < 0 || c1 >= C || c2 < 0 || c2 >= C) return INT_MIN;
if (memo[r][c1][c2] != INT_MIN) return memo[r][c1][c2];
int cur = grid[r][c1] + (c1 != c2 ? grid[r][c2] : 0);
if (r == R - 1) return memo[r][c1][c2] = cur;
int best = INT_MIN;
for (int d1 = -1; d1 <= 1; d1++) for (int d2 = -1; d2 <= 1; d2++) {
int nxt = solve(r + 1, c1 + d1, c2 + d2);
if (nxt > best) best = nxt;
}
return memo[r][c1][c2] = cur + best;
};
return solve(0, 0, C - 1);
}
};/**
* @param {number[][]} grid
* @return {number}
*/ var cherryPickup = function(grid) {
const R = grid.length, C = grid[0].length;
const memo = new Map();
const solve = (r, c1, c2) => {
if (c1 < 0 || c1 >= C || c2 < 0 || c2 >= C) return -Infinity;
const key = (r * 71 + c1) * 71 + c2;
if (memo.has(key)) return memo.get(key);
const cur = grid[r][c1] + (c1 !== c2 ? grid[r][c2] : 0);
if (r === R - 1) {
memo.set(key, cur);
return cur;
}
let best = -Infinity;
for (let d1 = -1; d1 <= 1; d1++) for (let d2 = -1; d2 <= 1; d2++) best = Math.max(best, solve(r + 1, c1 + d1, c2 + d2));
memo.set(key, cur + best);
return cur + best;
};
return solve(0, 0, C - 1);
};