Minimum Falling Path Sum II

Hard Topics Company Tags

Choose exactly one entry from each row of the square grid. Entries chosen in consecutive rows must be in different columns; the column may change by any nonzero distance. Return the smallest possible sum of the chosen entries.

Hatched cells show one minimum-sum path with different columns in adjacent rows.

Example 1:

Minimum Falling Path Sum II, example 1: illustration of the example

Input: grid = [[1,9],[2,8]]

Output: 9

Explanation: There are two valid choices: 1 followed by 8, or 9 followed by 2. The smaller sum is 9. Choosing 1 then 2 is forbidden because both occupy column 0.

Example 2:

Minimum Falling Path Sum II, example 2: illustration of the example

Input: grid = [[0,9,-2],[9,-3,9],[-4,9,9]]

Output: -9

Explanation: Choose -2 in column 2, then -3 in column 1, then -4 in column 0. Their sum is -9. Every adjacent pair uses different columns.

Example 3:

Minimum Falling Path Sum II, example 3: illustration of the example

Input: grid = [[5]]

Output: 5

Explanation: With one row, choose its only entry. There is no next row imposing a column restriction, so the result is 5.

Constraints:

  • 1 <= grid.length <= 200
  • Every row has grid.length entries.
  • -99 <= grid[i][j] <= 99


Topics

Company Tags

Please upgrade to NeetCode Pro to view company tags.