Min Cost Climbing Stairs
Easy
Topics
Given an array cost where cost[i] is the cost of step i, you can climb 1 or 2 steps and start from index 0 or 1. Return the minimum cost to reach the top (just past the last step).
Example 1
steps paid for
Each cell is the toll for standing on that step, and from a step you may climb one or two. You may start on either of the first two steps, and the top is above the last one — so the final step does not have to be paid for. The shaded steps cost 15 in total.
Cells are the array values; the small numbers underneath are indices.
Input: cost = [10,15,20] Output: 15
Example 2
steps paid for
Input: cost = [1,100,1,1,1,100,1,1,100,1] Output: 6
Constraints
- 2 <= cost.length <= 1000
- 0 <= cost[i] <= 999
Editorial — intuition, approach, complexity and pitfalls
Intuition
The cost to stand on a step is its own cost plus the cheaper of the two ways to get there (one or two steps below). Build these minimum costs upward; the top is just past the last step.
Approach
- Track the min cost to reach the previous two steps.
- For each step:
cost_here = step + min(prev, prevPrev). - Return
min(last, secondLast)since you can step onto the top from either.
Walkthrough
cost = [10, 15, 20]
reach step0=10, step1=15, step2=20+min(10,15)=30
top = min(step1, step2) = min(15, 30) = 15Complexity
- Time — O(n): one pass.
- Space — O(1): two rolling variables.
Common Pitfalls
- Return
b, nota. After the loopbis the cost of standing past the last step andais one step short of it, so returningagives 10 instead of 15 on the first example. - You may start at index 0 or index 1, which is why both
aandbbegin at 0 rather than atnums[0].
Full Solution — all languages
class Solution:
def minCostClimbingStairs(self, nums):
a = b = 0
for i in range(2, len(nums) + 1):
a, b = b, min(b + nums[i - 1], a + nums[i - 2])
return bimport java.util.*;
class Solution {
public int minCostClimbingStairs(int[] nums) {
int a = 0, b = 0;
for (int i = 2; i <= nums.length; i++) {
int t = Math.min(b + nums[i - 1], a + nums[i - 2]);
a = b;
b = t;
}
return b;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: int minCostClimbingStairs(vector<int>& nums) {
int a = 0, b = 0;
for (int i = 2; i <= (int)nums.size(); i++) {
int t = min(b + nums[i - 1], a + nums[i - 2]);
a = b;
b = t;
}
return b;
}
};/**
* @param {number[]} nums
* @return {number}
*/ var minCostClimbingStairs = function(nums) {
let a = 0, b = 0;
for (let i = 2; i <= nums.length; i++) {
const t = Math.min(b + nums[i - 1], a + nums[i - 2]);
a = b;
b = t;
}
return b;
};