746. Min Cost Climbing Stairs
Easy NeetCode 150 ↗ Open on LeetCode Source: NeetCode 150
Quick review
- Pattern
- 1-D Dynamic Programming
- Time
- O(N)
- Space
- O(1)
A standard reference solution for this problem is coming soon.
My Solution (C++)
#include <vector>
using namespace std;
class Solution {
public:
int minCostClimbingStairs(vector<int>& cost) {
// 1. f(k)=min(f(k-1)+cost(k-1), f(k-2)+cost(k-2)), f(0)=f(1)=0, start from n, recursively, without paying the kth cost
// 2. f(0)=f(1)=0, same formula, but start from 2 to n
// to save the memory, we can use only two vars to memorize the previous two nums
int prev2=0, prev1=0;
for(int i=2; i<=cost.size(); ++i){
int cur=std::min(prev2+cost[i-2], prev1+cost[i-1]);
prev2=prev1;
prev1=cur;
}
return prev1;
}
};
// Time Complexity: O(N)
// Space Complexity: O(1) Time O(N) Space O(1)
My own solution and notes, as I wrote them.
▶ Run it — editable in-browser playground with a sample driver C++
Your solution plus an auto-generated main() and sample input so Run produces output. The driver and inputs are unverified — edit freely; Reset restores this starting point.
C++ ▶ Runnable Auto-generated driver with sample input — unverified.
Runs in a free public sandbox (Wandbox). Output and timing include network latency; don't paste secrets.