MediumArrayDynamic ProgrammingMatrix

Minimum Falling Path Sum

LeetCode
1 approach, code in all languages

You are given a square integer grid. A falling path chooses exactly one number from every row, moving downward one row at a time.

When you drop from a cell in one row to the next row, the column can shift by at most one position: you may stay in the same column, move one column to the left, or move one column to the right. In other words, from column c you can land on column c - 1, c, or c + 1 in the row below (staying inside the grid).

Return the smallest possible sum obtainable by adding up the values along any single falling path.

Example 1

Input: matrix = [[2,1,3],[6,5,4],[7,8,9]]

Output: 13

One optimal path is 1 -> 5 -> 7 (sum 13). Another path 1 -> 4 -> 8 also totals 13; no path does better.

Example 2

Input: matrix = [[-19,57],[-40,-5]]

Output: -59

Choosing -19 from the top row and -40 from the bottom row (adjacent columns) gives the minimum sum -59.

Constraints

  • n == matrix.length == matrix[i].length
  • 1 <= n <= 100
  • -100 <= matrix[i][j] <= 100
You've got the patterns

Patterns get you through the screen. Shipping gets you hired.

FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.

750+ engineers trained · frontend, backend, AWS & AI

August 15 · 0d left
Enroll Now