2-D Dynamic Programming Paths in a grid
545. Cherry Pickup II
You are given a field of cherries as a grid with m rows and n columns. grid[i][j] is the number of
cherries in the cell at row i and column j.
Two robots start in the top row. Robot 1 starts in the top-left cell, (0, 0), and robot 2 in the
top-right cell, (0, n - 1). Both robots move down one row at a time, together, until they reach the
bottom row. From the cell (i, j), a robot moves to (i + 1, j - 1), (i + 1, j) or (i + 1, j + 1):
one column to the left, straight down, or one column to the right. A robot can never leave the grid.
A robot collects all the cherries in every cell it stands on, its starting cell included. When both robots stand on the same cell, its cherries are collected only once. Return the largest number of cherries the two robots can collect together.
Example 1
Input: grid = [[3, 1, 0, 2, 5],
[2, 6, 1, 0, 4],
[0, 1, 0, 7, 1],
[5, 2, 8, 1, 3]]
39Explanation: Robot 1 collects 3 → 6 → 1 → 5 and robot 2 collects 5 → 4 → 7 → 8, so together they collect 15 + 24 = 39. Robot 2 moves left twice to reach the 7 and the 8.
Example 2
Input: grid = [[3], [0], [5], [2]]
10Explanation: The grid has one column, so both robots start on the same cell and walk down it together. Each cell counts once: 3 + 0 + 5 + 2 = 10.
Example 3
Input: grid = [[1, 0, 0, 1], [0, 0, 0, 0], [0, 9, 0, 0]]
11Explanation: Both robots can reach the 9, but its cherries are collected only once. The answer is 1 + 1 + 9 = 11.
Check your understanding
Work out the answer for this input before you write any code.
Constraints
m == grid.length,n == grid[i].length1 ≤ m ≤ 10001 ≤ n ≤ 300 ≤ grid[i][j] ≤ 100
Clarifying questions
What you would ask an interviewer before writing any code.