LC746 - Min Cost Climbing Stairs
Problem
You are given an integer array cost where cost[i] is the cost of the i-th
step on a staircase. Once you pay the cost, you can either climb one or two steps. You can either start from the step with index 0
, or the step with index 1
. Return the minimum cost to reach the top of the floor
Example
Input: cost = [10, 15, 20]
Output: 15
Explanation: Cheapest is to start on cost[1], pay that cost, and reach the top.
Solution
Naive
Fill out all the edges to each node on the decision tree, which costs . Similar to the brute force solution of Climbing Stairs, except we count cost instead of steps. Then sum up the edges and return the minimum cost solution.
Dynamic Programming
Incrementally fill out the minimum cost to reach the end from a particular step, going from the top to bottom. This works because the min cost of each step is dependent on the min cost of the next two steps.
In theory, we don’t need to rewrite the array and only need to keep two variables, but this is the easiest/most intuitive way to code for me.
Time complexity of this solution is and space complexity is , since we don’t use any extra space save for temporary variables.
Last updated