741. Cherry Pickup
HardSolutions in Python, Java, C++, TypeScript
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
The problem asks for the maximum number of cherries we can collect by making a round trip: from (0, 0) to (n-1, n-1) moving only down or right, and then back from (n-1, n-1) to (0, 0) moving only up or left. When we pass through a cell with a cherry, we pick it, and the cell becomes empty. This means a cherry can be picked at most once during the entire round trip.
Solution
Cherry Pickup in Python
class Solution:
def cherryPickup(self, grid: List[List[int]]) -> int:
n = len(grid)
# dp[r1][r2] stores max cherries collected with person 1 at (r1, c1) and person 2 at (r2, c2)
# where c1 = k - r1 and c2 = k - r2
dp = [[-1] * n for _ in range(n)]
# Base case: at k=0, both persons are at (0,0)
dp[0][0] = grid[0][0]
# k is the total number of steps taken (manhattan distance from origin)
for k in range(1, 2 * n - 1):
new_dp = [[-1] * n for _ in range(n)]
# Iterate over all possible row positions for person 1 (r1) and person 2 (r2)
for r1 in range(n):
for r2 in range(n):
c1 = k - r1
c2 = k - r2
# Check if positions are valid
if not (0 <= c1 < n and 0 <= c2 < n and grid[r1][c1] != -1 and grid[r2][c2] != -1):
continue
# Get max cherries from previous step (k-1)
# The four previous states correspond to moves:
# P1 up, P2 up -> (r1-1, c1), (r2-1, c2) -> dp[r1-1][r2-1]
# P1 up, P2 left -> (r1-1, c1), (r2, c2-1) -> dp[r1-1][r2]
# P1 left, P2 up -> (r1, c1-1), (r2-1, c2) -> dp[r1][r2-1]
# P1 left, P2 left -> (r1, c1-1), (r2, c2-1) -> dp[r1][r2]
prev_cherries = -1
if r1 > 0 and r2 > 0 and dp[r1-1][r2-1] != -1: prev_cherries = max(prev_cherries, dp[r1-1][r2-1])
if r1 > 0 and dp[r1-1][r2] != -1: prev_cherries = max(prev_cherries, dp[r1-1][r2])
if r2 > 0 and dp[r1][r2-1] != -1: prev_cherries = max(prev_cherries, dp[r1][r2-1])
if dp[r1][r2] != -1: prev_cherries = max(prev_cherries, dp[r1][r2])
if prev_cherries == -1:
continue # This state is unreachable
# Add cherries from current cells
current_cherries = grid[r1][c1]
if r1 != r2: # If they are not in the same cell
current_cherries += grid[r2][c2]
new_dp[r1][r2] = prev_cherries + current_cherries
dp = new_dp # Move to the next step
# Final result is at the destination cell (n-1, n-1)
return max(0, dp[n - 1][n - 1])
Cherry Pickup in Java
class Solution {
public int cherryPickup(int[][] grid) {
int n = grid.length;
int[][] dp = new int[n][n];
// Initialize dp table with -1 to represent unreachability
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
dp[i][j] = -1;
}
}
// Base case: at k=0, both persons are at (0,0)
dp[0][0] = grid[0][0];
// k is the total number of steps taken (manhattan distance from origin)
for (int k = 1; k <= 2 * n - 2; k++) {
int[][] newDp = new int[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
newDp[i][j] = -1;
}
}
// Iterate over all possible row positions for person 1 (r1) and person 2 (r2)
for (int r1 = 0; r1 < n; r1++) {
for (int r2 = 0; r2 < n; r2++) {
int c1 = k - r1;
int c2 = k - r2;
// Check if positions are valid
if (c1 < 0 || c1 >= n || c2 < 0 || c2 >= n || grid[r1][c1] == -1 || grid[r2][c2] == -1) {
continue;
}
// Get max cherries from previous step (k-1)
int prevCherries = -1;
if (r1 > 0 && r2 > 0 && dp[r1 - 1][r2 - 1] != -1) prevCherries = Math.max(prevCherries, dp[r1 - 1][r2 - 1]);
if (r1 > 0 && dp[r1 - 1][r2] != -1) prevCherries = Math.max(prevCherries, dp[r1 - 1][r2]);
if (r2 > 0 && dp[r1][r2 - 1] != -1) prevCherries = Math.max(prevCherries, dp[r1][r2 - 1]);
if (dp[r1][r2] != -1) prevCherries = Math.max(prevCherries, dp[r1][r2]);
if (prevCherries == -1) {
continue; // This state is unreachable
}
// Add cherries from current cells
int currentCherries = grid[r1][c1];
if (r1 != r2) { // If they are not in the same cell
currentCherries += grid[r2][c2];
}
newDp[r1][r2] = prevCherries + currentCherries;
}
}
dp = newDp; // Move to the next step
}
// Final result is at the destination cell (n-1, n-1)
return Math.max(0, dp[n - 1][n - 1]);
}
}
Cherry Pickup in C++
class Solution {
public:
int cherryPickup(vector<vector<int>>& grid) {
int n = grid.size();
vector<vector<int>> dp(n, vector<int>(n, -1));
// Base case: at k=0, both persons are at (0,0)
dp[0][0] = grid[0][0];
// k is the total number of steps taken (manhattan distance from origin)
for (int k = 1; k <= 2 * n - 2; ++k) {
vector<vector<int>> new_dp(n, vector<int>(n, -1));
// Iterate over all possible row positions for person 1 (r1) and person 2 (r2)
for (int r1 = 0; r1 < n; ++r1) {
for (int r2 = 0; r2 < n; ++r2) {
int c1 = k - r1;
int c2 = k - r2;
// Check if positions are valid
if (c1 < 0 || c1 >= n || c2 < 0 || c2 >= n || grid[r1][c1] == -1 || grid[r2][c2] == -1) {
continue;
}
// Get max cherries from previous step (k-1)
int prev_cherries = -1;
if (r1 > 0 && r2 > 0 && dp[r1 - 1][r2 - 1] != -1) prev_cherries = max(prev_cherries, dp[r1 - 1][r2 - 1]);
if (r1 > 0 && dp[r1 - 1][r2] != -1) prev_cherries = max(prev_cherries, dp[r1 - 1][r2]);
if (r2 > 0 && dp[r1][r2 - 1] != -1) prev_cherries = max(prev_cherries, dp[r1][r2 - 1]);
if (dp[r1][r2] != -1) prev_cherries = max(prev_cherries, dp[r1][r2]);
if (prev_cherries == -1) {
continue; // This state is unreachable
}
// Add cherries from current cells
int current_cherries = grid[r1][c1];
if (r1 != r2) { // If they are not in the same cell
current_cherries += grid[r2][c2];
}
new_dp[r1][r2] = prev_cherries + current_cherries;
}
}
dp = new_dp; // Move to the next step
}
// Final result is at the destination cell (n-1, n-1)
return max(0, dp[n - 1][n - 1]);
}
};
Cherry Pickup in TypeScript
function cherryPickup(grid: number[][]): number {
const n = grid.length;
let dp: number[][] = Array(n).fill(0).map(() => Array(n).fill(-1));
// Base case: at k=0, both persons are at (0,0)
dp[0][0] = grid[0][0];
// k is the total number of steps taken (manhattan distance from origin)
for (let k = 1; k <= 2 * n - 2; k++) {
let newDp: number[][] = Array(n).fill(0).map(() => Array(n).fill(-1));
// Iterate over all possible row positions for person 1 (r1) and person 2 (r2)
for (let r1 = 0; r1 < n; r1++) {
for (let r2 = 0; r2 < n; r2++) {
const c1 = k - r1;
const c2 = k - r2;
// Check if positions are valid
if (c1 < 0 || c1 >= n || c2 < 0 || c2 >= n || grid[r1][c1] === -1 || grid[r2][c2] === -1) {
continue;
}
// Get max cherries from previous step (k-1)
let prevCherries = -1;
if (r1 > 0 && r2 > 0 && dp[r1 - 1][r2 - 1] !== -1) prevCherries = Math.max(prevCherries, dp[r1 - 1][r2 - 1]);
if (r1 > 0 && dp[r1 - 1][r2] !== -1) prevCherries = Math.max(prevCherries, dp[r1 - 1][r2]);
if (r2 > 0 && dp[r1][r2 - 1] !== -1) prevCherries = Math.max(prevCherries, dp[r1][r2 - 1]);
if (dp[r1][r2] !== -1) prevCherries = Math.max(prevCherries, dp[r1][r2]);
if (prevCherries === -1) {
continue; // This state is unreachable
}
// Add cherries from current cells
let currentCherries = grid[r1][c1];
if (r1 !== r2) { // If they are not in the same cell
currentCherries += grid[r2][c2];
}
newDp[r1][r2] = prevCherries + currentCherries;
}
}
dp = newDp; // Move to the next step
}
// Final result is at the destination cell (n-1, n-1)
return Math.max(0, dp[n - 1][n - 1]);
}
More Hard LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.