Leetcode #1463: Cherry Pickup II
In this guide, we solve Leetcode #1463 Cherry Pickup II in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
You are given a rows x cols matrix grid representing a field of cherries where grid[i][j] represents the number of cherries that you can collect from the (i, j) cell. You have two robots that can collect cherries for you: Robot #1 is located at the top-left corner (0, 0), and Robot #2 is located at the top-right corner (0, cols - 1).
Quick Facts
- Difficulty: Hard
- Premium: No
- Tags: Array, Dynamic Programming, Matrix
Intuition
The problem breaks into overlapping subproblems, so caching results prevents exponential repetition.
A carefully chosen DP state captures exactly what we need to build the final answer.
Approach
Define the DP state and recurrence, then compute states in the correct order.
Optionally compress space once the recurrence is clear.
Steps:
- Choose a DP state definition.
- Write the recurrence and base cases.
- Compute states in the correct order.
Example
Input: grid = [[3,1,1],[2,5,1],[1,5,5],[2,1,1]]
Output: 24
Explanation: Path of robot #1 and #2 are described in color green and blue respectively.
Cherries taken by Robot #1, (3 + 2 + 5 + 2) = 12.
Cherries taken by Robot #2, (1 + 5 + 5 + 1) = 12.
Total of cherries: 12 + 12 = 24.
Python Solution
class Solution:
def cherryPickup(self, grid: List[List[int]]) -> int:
m, n = len(grid), len(grid[0])
f = [[[-1] * n for _ in range(n)] for _ in range(m)]
f[0][0][n - 1] = grid[0][0] + grid[0][n - 1]
for i in range(1, m):
for j1 in range(n):
for j2 in range(n):
x = grid[i][j1] + (0 if j1 == j2 else grid[i][j2])
for y1 in range(j1 - 1, j1 + 2):
for y2 in range(j2 - 1, j2 + 2):
if 0 <= y1 < n and 0 <= y2 < n and f[i - 1][y1][y2] != -1:
f[i][j1][j2] = max(f[i][j1][j2], f[i - 1][y1][y2] + x)
return max(f[-1][j1][j2] for j1, j2 in product(range(n), range(n)))
Complexity
The time complexity is , and the space complexity is . The space complexity is .
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.