CodeArchon

easy1-D Dynamic ProgrammingAmazonMicrosoft

Treadmill Ticket Cheapskate

A gym chain charges a per-step entry fee; a budgeter wants the minimum total toll to pass through to the top floor using 1- or 2-step hops.

Given a cost array where cost[i] is the fee for using step i, you can start at index 0 or 1. From each step hop 1 or 2 forward. Return the minimum total cost to reach the top.

Choose approach

0
0
0
1
?
2
?
3
i
1/4
Narrationstep 1 of 4

Base: dp[0] = dp[1] = 0 (free entry from the ground).

1def minCostClimbingStairs(cost):
2 n = len(cost)
3 dp = [0] * (n + 1)
4 for i in range(2, n + 1):
5 dp[i] = min(dp[i-1] + cost[i-1], dp[i-2] + cost[i-2])
6 return dp[n]
Variables

How to think about it

  1. Pay only when you land on a step (except the top).
  2. Two choices for each landing.

Edge cases to catch in interview

  • n = 2 -> min(cost[0], cost[1]).
  • Alternating big/small costs stress the min.

Examples

Example 16
{"cost":[1,100,1,1,1,100,1,1,100,1]}

Try your own input

SpacePlay / pause
← / →Previous / next step
RReset to start
. or >Cycle speed