Leetcode #741: Cherry Pickup
In this guide, we solve Leetcode #741 Cherry Pickup 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 an n x n grid representing a field of cherries, each cell is one of three possible integers. 0 means the cell is empty, so you can pass through, 1 means the cell contains a cherry that you can pick up and pass through, or -1 means the cell contains a thorn that blocks your way.
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 = [[0,1,-1],[1,0,-1],[1,1,1]]
Output: 5
Explanation: The player started at (0, 0) and went down, down, right right to reach (2, 2).
4 cherries were picked up during this single trip, and the matrix becomes [[0,1,-1],[0,0,-1],[0,0,0]].
Then, the player went left, up, up, left to return home, picking up one more cherry.
The total number of cherries picked up is 5, and this is the maximum possible.
Python Solution
class Solution:
def cherryPickup(self, grid: List[List[int]]) -> int:
n = len(grid)
f = [[[-inf] * n for _ in range(n)] for _ in range((n << 1) - 1)]
f[0][0][0] = grid[0][0]
for k in range(1, (n << 1) - 1):
for i1 in range(n):
for i2 in range(n):
j1, j2 = k - i1, k - i2
if (
not 0 <= j1 < n
or not 0 <= j2 < n
or grid[i1][j1] == -1
or grid[i2][j2] == -1
):
continue
t = grid[i1][j1]
if i1 != i2:
t += grid[i2][j2]
for x1 in range(i1 - 1, i1 + 1):
for x2 in range(i2 - 1, i2 + 1):
if x1 >= 0 and x2 >= 0:
f[k][i1][i2] = max(f[k][i1][i2], f[k - 1][x1][x2] + t)
return max(0, f[-1][-1][-1])
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.