CodingNodes / 1-D Dynamic Programming / Min Cost Climbing Stairs System design Space play · ←→ step · R restart

Problem

cost[i] is the price you pay to leave step i, after which you climb either 1 or 2 steps. You may start on step 0 or on step 1. The top is the position just past the last step, index cost.length.

Return the smallest total price needed to reach the top.

Constraints

  • 2 ≤ cost.length ≤ 1000
  • 0 ≤ cost[i] ≤ 999

Examples: pick one to animate

Solutions

TimeO(n) SpaceO(n)

Time: One pass over steps 2 to n, comparing two options for each step.

Space: The dp array holds n + 1 costs.

dp[i] is the cheapest way to stand on step i. You arrive from step i-1 after paying cost[i-1], or from step i-2 after paying cost[i-2], so take the smaller. Steps 0 and 1 are free starts.