oneby7

2-D Dynamic Programming Paths in a grid

545. Cherry Pickup II

Hard

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

31025261040107152813

Input: grid = [[3, 1, 0, 2, 5], [2, 6, 1, 0, 4], [0, 1, 0, 7, 1], [5, 2, 8, 1, 3]]

Output: 39

Explanation: 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

3052

Input: grid = [[3], [0], [5], [2]]

Output: 10

Explanation: 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

100100000900

Input: grid = [[1, 0, 0, 1], [0, 0, 0, 0], [0, 9, 0, 0]]

Output: 11

Explanation: 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.

grid = [[9, 8, 7], [0, 6, 4], [2, 8, 0]]

Constraints

  • m == grid.length, n == grid[i].length
  • 1 ≤ m ≤ 1000
  • 1 ≤ n ≤ 30
  • 0 ≤ grid[i][j] ≤ 100

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.