Cherry Pickup
ID: 1463
Last updated
ID: 1463
Last updated
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
.
Since the movement of robot1 and robot2 can interact with each other, meaning that we cannot calculate robot1 first and then calculate robot2, so that we need to move robot 1 and 2 at the same time.
Therefore, they will always be on the same row but different columns. So we can build a dp array of [grid.length][grid[0].length][grid[0].length].
Each index of dp array has the meaning of the largest value that can be obtained from robot1 at [row][c1] and robot2 at [row][c2]. For example, dp[3][0][3] means the largest cherry pick that can be obtained from robot1 at 3,0 in grid, and robot2 at 3,3 in grid
Therefore, we can apply bottom up approach so that the last row of the grid is just the value itself. If robot 1 and 2 are not having the same column number, they can get two cherry pick values in the grid. But if they are having the same column number, they can only get a single cherry pick value.
For topper layers from the last row, each index of dp can be calculated from the max of all 9 combinations of 3 direction and 2 robots movements.
Finally, we can pop the dp[0][0][grid[0].length-1] to get the max cherry pick count when starting from the top left and top right corner of the grid