Cherry Pickup solution explained

Cherry Pickup asks for the most items you can collect on a trip from the top-left corner of a square grid to the bottom-right corner and back, without crossing blocked cells and counting each cell once. Treat the return trip as a second forward trip and move two walkers together, one step at a time; after the same number of steps they can only share a cell if they are in the same row. A DP over (step, row of walker 1, row of walker 2) solves it in O(n³) time and O(n²) space.

By Published 10 min read

The problem, in plain terms

You get an n by n grid. A cell holds 1 (a cherry), 0 (empty) or -1 (a thorn you cannot step on). Start in the top-left cell, walk to the bottom-right cell using only right and down moves, then walk back to the start using only left and up moves. Every cherry you step on is picked up, so the same cell pays at most once even if both legs pass through it. Return the largest number of cherries you can end with, or 0 if no valid route to the far corner exists.

0  1  1  0
1 -1  1  1
1  1  0 -1
0  1  1  0

out:  down, down, right, down, right, right   picks 5
back: retrace a route through row 1 and down column 3, picking 3 more
total: 8 of the 9 cherries

The cherry in row 2, column 4 cannot be reached: from there the only move
is down, onto the thorn below it.
A worked example, made up for this page (rows and columns counted from 1)

Questions worth asking first: is the grid always square, can the start or the end be a thorn, and what should come back when the end is unreachable. Those answers decide the first two lines of your code.

Why interviewers ask it

It looks like an easy grid DP with a twist, and the twist is the whole question. Most candidates first try to solve each leg separately, and the interviewer wants to see whether you can find a reason that fails and then change the state you track. It also tests whether you can explain a three-index DP clearly, which is harder than writing one.

Why two greedy trips fail

The tempting plan: take the single best route out, remove the cherries it collected, then take the best route on what is left. On the grid below, every best first route picks up 4 cherries along row 2 and then down column 3. What remains are the cherries in row 1, column 3 and row 4, column 2, and no right-and-down route can visit both, because the first sits to the right of the second. The greedy total is 5. Two coordinated routes do better: one along the top and down column 3, the other down column 1, across row 2 and down column 2, for 6.

0 0 1 0
1 1 1 0
0 0 1 0
0 1 0 0
Greedy gets 5, the best pair of routes gets 6

The lesson is that the two legs compete for the same cherries, so they have to be planned together.

Brute force

Since the return leg read backwards is just another right-and-down route, the problem is: choose two right-and-down routes from corner to corner and maximize the cherries in the union of their cells. The brute force lists every route that avoids thorns and tries every pair. An n by n grid has C(2n - 2, n - 1) routes, which is 20 for n = 4 and grows exponentially, so pairing them is only usable as a test reference on tiny grids. That is exactly how we used it to check the fast version.

The key idea: two walkers in step

Pattern: multi-dimensional dynamic programming with a synchronized state. Move both walkers forward at the same time, one step each per round. After t steps, a walker in row r must be in column t - r, so the pair of rows (r1, r2) is enough to describe where both are. Because both have taken t steps, they stand on the same cell exactly when r1 equals r2, and that is the only way they can share a cell at all: two routes can only overlap at cells reached after the same number of moves. So the gain for a round is the cherry under walker 1 plus the cherry under walker 2, counted once if they share the cell.

Each walker arrived either from the left or from above, so there are four ways the previous round could have looked: (r1, r2), (r1 - 1, r2), (r1, r2 - 1) and (r1 - 1, r2 - 1). Take the best of those that were reachable, add the gain, and skip any state where either walker stands on a thorn.

def cherry_pickup(grid):
    n = len(grid)
    if grid[0][0] == -1 or grid[n - 1][n - 1] == -1:
        return 0
    NEG = float("-inf")
    # best[r1][r2]: most cherries so far with walker 1 in row r1 and
    # walker 2 in row r2, both having taken the same number of steps
    best = [[NEG] * n for _ in range(n)]
    best[0][0] = grid[0][0]
    for step in range(1, 2 * n - 1):
        nxt = [[NEG] * n for _ in range(n)]
        lo, hi = max(0, step - n + 1), min(n - 1, step)
        for r1 in range(lo, hi + 1):
            c1 = step - r1
            if grid[r1][c1] == -1:
                continue
            for r2 in range(lo, hi + 1):
                c2 = step - r2
                if grid[r2][c2] == -1:
                    continue
                came_from = best[r1][r2]                 # both stepped right
                if r1:
                    came_from = max(came_from, best[r1 - 1][r2])
                if r2:
                    came_from = max(came_from, best[r1][r2 - 1])
                if r1 and r2:
                    came_from = max(came_from, best[r1 - 1][r2 - 1])
                if came_from == NEG:
                    continue
                gain = grid[r1][c1]
                if r1 != r2:                             # same cell counts once
                    gain += grid[r2][c2]
                nxt[r1][r2] = came_from + gain
        best = nxt
    return max(best[n - 1][n - 1], 0)
Python: one table per step count, rows of both walkers as the index. Run against the brute force on 4,000 grids.

Negative infinity marks states no valid pair of routes can reach. The final max with 0 turns an unreachable corner into the required answer of 0. On the worked example the function returns 8, and on the greedy trap it returns 6.

C++ version with the symmetry trick

The two walkers are interchangeable, so the state (r1, r2) has the same value as (r2, r1). The C++ version only fills cells with r1 ≤ r2, which roughly halves the work. The catch is the predecessor (r1, r2 - 1): when r1 equals r2 it has the smaller row second, so the code reads it with min and max to land in the stored half.

#include <algorithm>
#include <climits>
#include <vector>
using namespace std;

int cherryPickup(const vector<vector<int>>& grid) {
    const int n = grid.size();
    const int NEG = INT_MIN / 2;          // "unreachable", safe to add to
    if (grid[0][0] == -1 || grid[n - 1][n - 1] == -1) return 0;
    vector<vector<int>> best(n, vector<int>(n, NEG)), nxt;
    best[0][0] = grid[0][0];
    for (int step = 1; step <= 2 * n - 2; ++step) {
        nxt.assign(n, vector<int>(n, NEG));
        int lo = max(0, step - n + 1), hi = min(n - 1, step);
        for (int r1 = lo; r1 <= hi; ++r1) {
            int c1 = step - r1;
            if (grid[r1][c1] == -1) continue;
            for (int r2 = r1; r2 <= hi; ++r2) {   // walkers are interchangeable
                int c2 = step - r2;
                if (grid[r2][c2] == -1) continue;
                int from = best[r1][r2];
                if (r1 > 0) from = max(from, best[r1 - 1][r2]);
                if (r2 > 0) from = max(from, best[min(r1, r2 - 1)][max(r1, r2 - 1)]);
                if (r1 > 0 && r2 > 0) from = max(from, best[r1 - 1][r2 - 1]);
                if (from <= NEG / 2) continue;
                int gain = grid[r1][c1] + (r1 != r2 ? grid[r2][c2] : 0);
                nxt[r1][r2] = from + gain;
            }
        }
        swap(best, nxt);
    }
    return max(best[n - 1][n - 1], 0);
}
C++17: half the table by symmetry. Compiled with clang++ and checked on the same random grids plus larger ones.

INT_MIN / 2 is used instead of INT_MIN so that adding a small gain to an unreachable value cannot overflow, and the reachability test compares against a threshold rather than the exact sentinel.

Complexity summary

n is the side length of the grid
ApproachTimeExtra space
Every pair of routesO(C(2n - 2, n - 1)² × n)O(number of routes × n) to store them
Two greedy tripsO(n²) per trip, but wrongO(n²)
Two walkers, full tableO(n³)O(n²), two layers of rows
Two walkers, symmetric halfO(n³) with about half the workO(n²)
n is the side length of the grid. Scroll sideways on a small screen.

There are 2n - 1 step counts and at most n × n row pairs per step, each settled in constant time, which gives the cubic bound. A full 3D memo table indexed by (t, r1, r2) is also fine and is often easier to write top-down; it just keeps O(n³) memory instead of two layers.

Edge cases to test

  • A one-by-one grid: the answer is that cell's value, or 0 if it is a thorn.
  • Thorns that cut every route, such as a 2 by 2 grid with thorns on the other diagonal: the answer is 0, not negative infinity.
  • A grid with no cherries at all: 0, through a valid route.
  • Both walkers forced through the same narrow corridor, to check the shared cell is counted once.
  • Cherries that only one route can reach, like the stranded cherry in the worked example.

Common mistakes

  • Running the greedy two-pass plan and trusting it because it passes the first example.
  • Tracking the walkers by full coordinates (r1, c1, r2, c2) without noticing that the step count makes columns redundant, which turns O(n³) into O(n⁴) states.
  • Adding both cells' cherries when the walkers share a cell.
  • Returning the raw DP value when the end is unreachable, which leaks the sentinel into the answer.
  • Starting the loop at the wrong step or stopping one step early; the last step index is 2n - 2.

How to explain it out loud

Fictional example

Turning a round trip into two forward trips
Candidate
My first instinct is to take the best path, clear it, and take the best path again, but the two trips fight over the same cherries, so I don't trust that. I'll treat the way back as a second path going forward.
Candidate
If I move both paths one step at a time, after t steps each walker's column is t minus its row. So I only need t and the two rows, and they share a cell only when the rows match.
Candidate
Each walker came from the left or from above, which gives four previous states. That's n cubed time overall, and I can keep just two layers of the table for n squared memory.

The one-walker version of this idea, with a single cheapest route, is Minimum Path Sum. A row-by-row DP where each step can jump to any column is Minimum Path Cost in a Grid. For a DP whose state is a small set of counters rather than positions, compare Student Attendance Record II.

Rehearsing it with Natively

The hard part of this problem is the moment you change the state, and that is worth rehearsing out loud. During practice on a Mac or Windows computer, Natively can read a grid problem from a screenshot and write an approach with code, so you can set its version next to your own two-walker DP. Its transcript of the session shows whether you explained the step-count trick before you started typing. More on practicing with an AI coding interview helper.

Questions people ask

How do you solve Cherry Pickup?

Turn the trip back into a second trip forward and move two walkers together. After t steps each walker's column is t minus its row, so a DP over the step and the two rows finds the best total, counting a shared cell once.

Why doesn't taking the best path twice work for Cherry Pickup?

The two trips compete for the same cherries. Taking the richest single route first can leave the remaining cherries where no second route can reach them all, while two routes planned together collect more.

What is the time complexity of Cherry Pickup?

O(n³) time for an n by n grid: about 2n step counts times n² pairs of rows, each settled in constant time. Space is O(n²) if you keep only the current and previous step.

How do you avoid counting a cherry twice in Cherry Pickup?

Because both walkers have taken the same number of steps, they can only be on the same cell when their rows are equal. In that case add the cell's value once instead of twice.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP