Ctrl K

Cheapest Way Down the Pyramid

Medium
Numbers are stacked into a pyramid: row i (0-based) holds exactly i + 1 numbers, and pyramid[i][j] is the fee for stepping on cell j of that row. You start at the apex pyramid[0][0] and go down one row per step until you reach the bottom. From cell j you may step to cell j or j + 1 of the row below. The cost of the descent is the sum of every number on the way, the apex and the bottom cell included. Return the minimum cost of a descent. Try to use only O(n) extra memory, where n is the number of rows.
Example 1
pyramid=[[3], [7, 1], [2, 9, 4], [8, 5, 6, 1]] → 9

The cheapest is 3 → 1 → 4 → 1, totalling 9. Greed doesn't always pay: going through 7 and 2 already costs 3 + 7 + 2 + 5 = 17.

Example 2
pyramid=[[-2], [5, -6]] → -8

From the apex step down to −6: −2 + (−6) = −8.

Example 3
pyramid=[[4]] → 4
Constraints
  • 1 ≤ len(pyramid) ≤ 200
  • len(pyramid[i]) = i + 1
  • -10⁴ ≤ pyramid[i][j] ≤ 10⁴
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsFewest Jumps to the End MediumMost Profitable Streak MediumReach the Last Cell MediumWarehouse Cart Routes MediumCheapest Corner-to-Corner Route Medium
loading Python…
Input
pyramid=[[3], [7, 1], [2, 9, 4], [8, 5, 6, 1]]
Expected
9

Run checks the first 3 tests in your browser. Submit checks all 90 tests on the server, hidden ones included.