Problem
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)
.
Return the maximum number of cherries collection using both robots by following the rules below:
- From a cell
(i, j)
, robots can move to cell(i + 1, j - 1)
,(i + 1, j)
, or(i + 1, j + 1)
. - When any robot passes through a cell, It picks up all cherries, and the cell becomes an empty cell.
- When both robots stay in the same cell, only one takes the cherries.
- Both robots cannot move outside of the grid at any moment.
- Both robots should reach the bottom row in
grid
.
Examples
Example 1
|
|
Example 2
|
|
Solution
Method 1 – Dynamic Programming with Memoization
Intuition: We use 3D dynamic programming to track the maximum cherries both robots can collect as they move row by row. At each step, both robots have 3 possible moves, and we recursively try all combinations, caching results to avoid recomputation.
Approach:
- Define a DP function
dp(r, c1, c2)
wherer
is the current row,c1
andc2
are the columns of robot 1 and 2. - If either robot moves out of bounds, return 0.
- Collect cherries at
(r, c1)
and(r, c2)
. If both robots are at the same cell, only count once. - For the next row, try all 9 combinations of moves for both robots (
-1, 0, 1
for each). - Memoize results for each
(r, c1, c2)
to avoid recomputation. - Start from row 0, columns 0 and
cols-1
.
Code
|
|
|
|
|
|
|
|
|
|
|
|
Complexity
- ⏰ Time complexity:
O(rows * cols * cols * 9)
=O(rows * cols^2)
- 🧺 Space complexity:
OO(rows * cols^2)
for memoization
Method 2 – Bottom-Up Dynamic Programming (Tabulation)
Intuition
Instead of solving subproblems recursively, we build the solution from the bottom row up. For each row and every possible pair of robot positions, we compute the maximum cherries that can be collected, using previously computed results for the next row. This avoids recursion and stack overhead.
Approach
- Let
dp[r][c1][c2]
represent the maximum cherries collected starting from rowr
with robots at columnsc1
andc2
. - Initialize the base case for the last row: for every pair
(c1, c2)
, sum the cherries at those positions (count once if same cell). - Iterate from the second-last row up to the first row.
- For each possible pair of columns
(c1, c2)
for the two robots, try all 9 combinations of moves for the next row (-1, 0, 1
for each robot). - For each move, add the cherries at
(r, c1)
and(r, c2)
(count once if same cell), plus the best result from the next row. - The answer is
dp[0][0][cols-1]
.
C++
|
|
Go
|
|
Java
|
|
Kotlin
|
|
Python
|
|
Rust
|
|
Complexity
- ⏰ Time complexity:
O(rows * cols^2 * 9)
=O(rows * cols^2)
- 🧺 Space complexity:
O(rows * cols^2)