Cherry Pickup II
HARDDescription
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.
Example 1:
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.
Example 2:
Input: grid = [[1,0,0,0,0,0,1],[2,0,0,0,0,3,0],[2,0,9,0,0,0,0],[0,3,0,5,4,0,0],[1,0,2,3,0,0,6]] Output: 28 Explanation: Path of robot #1 and #2 are described in color green and blue respectively. Cherries taken by Robot #1, (1 + 9 + 5 + 2) = 17. Cherries taken by Robot #2, (1 + 3 + 4 + 3) = 11. Total of cherries: 17 + 11 = 28.
Constraints:
rows == grid.lengthcols == grid[i].length2 <= rows, cols <= 700 <= grid[i][j] <= 100
Approaches
Checkout 3 different approaches to solve Cherry Pickup II. Click on different approaches to view the approach and algorithm in detail.
Brute-Force Recursion
This approach directly translates the problem's state transitions into a recursive function. The state is defined by the current row and the column positions of the two robots. Since both robots move down one row at a time, they are always in the same row.
Algorithm
- Define a recursive function
solve(row, col1, col2)that returns the maximum cherries collected from the currentrowdownwards, with robots at(row, col1)and(row, col2). - Base Case: If
rowis the last row, return the cherries at the robots' positions. Ifcol1orcol2are out of bounds, return a very small number to signify an invalid path. - Recursive Step: For the current state
(row, col1, col2), calculate the cherries collected at this step. Then, explore all 9 possible next positions (col1 + d1,col2 + d2whered1, d2are in{-1, 0, 1}) in the next row by making recursive calls. - The result for the current state is the sum of current cherries and the maximum value returned from the 9 recursive calls.
- The initial call is
solve(0, 0, cols - 1).
We define a recursive function, say solve(row, col1, col2), which calculates the maximum cherries that can be collected from the current row to the bottom, given robot 1 is at (row, col1) and robot 2 is at (row, col2). The function works as follows:
- Base Case: When the robots reach the last row (
row == rows - 1), they collect the cherries in their respective cells and the recursion stops. The value returned isgrid[row][col1] + grid[row][col2](or justgrid[row][col1]if they are in the same cell). - Recursive Step: For any other row, the function calculates the cherries collected at the current cells. Then, it explores all possible next moves for both robots. Robot 1 can move to
col1-1,col1, orcol1+1in the next row, and similarly for robot 2. This gives3 * 3 = 9possible combinations of next positions. The function recursively calls itself for each of these 9 combinations and takes the maximum result. This maximum is added to the cherries collected at the current row. - Boundary Checks: The function must handle cases where a robot moves outside the grid boundaries. Such paths are invalid and should return a value that ensures they are not chosen (e.g., a very small negative number).
- The initial call to the function is
solve(0, 0, cols - 1).
class Solution {
public int cherryPickup(int[][] grid) {
int rows = grid.length;
int cols = grid[0].length;
return solve(0, 0, cols - 1, grid);
}
private int solve(int row, int col1, int col2, int[][] grid) {
int rows = grid.length;
int cols = grid[0].length;
// Boundary checks for columns
if (col1 < 0 || col1 >= cols || col2 < 0 || col2 >= cols) {
return Integer.MIN_VALUE;
}
// Cherries at the current step
int cherries = grid[row][col1];
if (col1 != col2) {
cherries += grid[row][col2];
}
// Base case: last row
if (row == rows - 1) {
return cherries;
}
// Recursive step: explore all 9 possible next moves
int maxFutureCherries = 0;
for (int dc1 = -1; dc1 <= 1; dc1++) {
for (int dc2 = -1; dc2 <= 1; dc2++) {
maxFutureCherries = Math.max(maxFutureCherries, solve(row + 1, col1 + dc1, col2 + dc2, grid));
}
}
return cherries + maxFutureCherries;
}
}
Complexity Analysis
Pros and Cons
- Simple to understand and implement as it directly models the problem statement.
- Extremely inefficient due to a massive number of redundant computations for the same subproblems.
- Will result in a 'Time Limit Exceeded' error on any non-trivial input size.
Code Solutions
Checking out 3 solutions in different languages for Cherry Pickup II. Click on different languages to view the code.
Video Solution
Watch the video walkthrough for Cherry Pickup II
Similar Questions
5 related questions you might find useful
Patterns:
Data Structures:
Companies:
Subscribe to Scale Engineer newsletter
Learn about System Design, Software Engineering, and interview experiences every week.
No spam, unsubscribe at any time.