← All coding problems
Min Cost Climbing Stairs
easyDynamic Programming+10 XPTime limit 2s
cost[i] is the price of stepping on stair i. Once you pay for a stair, you may climb one or two stairs. You may start on stair 0 or stair 1. The top is just past the last stair. Find the minimum total cost to reach the top.
Input:
- line 1:
n - line 2:
ncosts
Output: the minimum cost.
Constraints: 2 ≤ n ≤ 10⁵, 0 ≤ cost ≤ 999.
Think about it: best[i] = min(best[i−1] + cost[i−1], best[i−2] + cost[i−2]) — and you only ever need the last two values, so O(1) memory.
Sample input 1
3 10 15 20
Sample output 1
15
Sample input 2
10 1 100 1 1 1 100 1 1 100 1
Sample output 2
6
📖 Stuck? Learn the pattern
Read input from standard input and print the answer to standard output. Your code runs in a secure sandbox against the samples (Run) and hidden tests (Submit).