Cherry Pickup II

Hard

Topics
ArrayDynamic ProgrammingMatrix

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

0311125121553211012
robot 1 startsrobot 2 starts
Two robots walk down simultaneously, one from each top corner, each moving one row down and at most one column sideways. They collect every cell they land on, but a cell shared in the same row is counted once — which is why the state has to track both columns together rather than running two independent paths.
2D grid — one row per line.
Input:  grid = [[3,1,1],[2,5,1],[1,5,5],[2,1,1]]
Output: 24

Example 2

050
robot 1 starts
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

  1. Define solve(row, c1, c2) as the best total collectable from this row downward.
  2. Return negative infinity if either column is off the grid, so illegal moves lose.
  3. Collect grid[row][c1] + grid[row][c2], or just one of them when c1 == c2.
  4. On the last row, stop. Otherwise take the best of the 9 next-row combinations and add it.
  5. 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 × cols layers 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 == c2 only one robot collects.
  • Memoising on (row, c1, c2) but allowing c1 > c2 to be a distinct state from (row, c2, c1). It is correct, just twice the table; enforcing c1 <= c2 halves 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)
Asked at Flipkart Sprinklr
SensAI
Beta
Tap the mic to stop voice mode