Skip to the code
cf.
+10 XP

#506 Cheapest Drop Through a Price Matrix

easy

A pricing page compares plans in an n by n matrix, where matrix[r][c] is a price. You build a path from the top row to the bottom row by choosing one cell in each row. From cell (r, c), the next cell must be in row r + 1 and column c - 1, c, or c + 1.

Write cheapestDrop(matrix) that returns the smallest possible sum of the cells on such a path. Prices can be negative (discounts).

Example 1

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

2, then 5, then 1.

Example 2

Input: matrix = [[-10,40],[-30,-4]]
Output: -40

-10, then -30.

Constraints

  • 1 <= n <= 100
  • -100 <= matrix[r][c] <= 100
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).