Min Cost Climbing Stairs Problem
Description
LeetCode Problem 746.
You are given an integer array cost where cost[i] is the cost of 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 1:
Input: cost = [10,15,20]
Output: 15
Explanation: You will start at index 1.
- Pay 15 and climb two steps to reach the top.
The total cost is 15.
Example 2:
Input: cost = [1,100,1,1,1,100,1,1,100,1]
Output: 6
Explanation: You will start at index 0.
- Pay 1 and climb two steps to reach index 2.
- Pay 1 and climb two steps to reach index 4.
- Pay 1 and climb two steps to reach index 6.
- Pay 1 and climb one step to reach index 7.
- Pay 1 and climb two steps to reach index 9.
- Pay 1 and climb one step to reach the top.
The total cost is 6.
Constraints:
- 2 <= cost.length <= 1000
- 0 <= cost[i] <= 999
Solution
Approach: Dynamic Programming with Two Variables
Number the steps 0 to n - 1 and call the top step n. Let reach(i) be the cheapest total cost to stand on step i, before paying that step's own cost.
reach(0) = reach(1) = 0, because we may start on either step for free.- To stand on step
i, the last move came from stepi - 1(paycost[i - 1], climb one) or from stepi - 2(paycost[i - 2], climb two):reach(i) = min(reach(i - 1) + cost[i - 1], reach(i - 2) + cost[i - 2]). - The answer is
reach(n).
Each value depends only on the two before it, so two variables, reachTwoBack and reachOneBack, replace the whole table. They slide forward one step per iteration.
The detail people get wrong is where the top is. The top is past the last step, at index n, not the last step itself. In the first example, cost = [10, 15, 20]: reach(2) = min(0 + 15, 0 + 10) = 10, and reach(3) = min(10 + 20, 0 + 15) = 15. Stopping at step 2 would give 10, which never reaches the top.
Complexity: O(n) time, where n is the length of cost, and O(1) space.
class Solution:
def minCostClimbingStairs(self, cost: List[int]) -> int:
# reach(i) = cheapest way to stand on step i; the top is step len(cost).
# Steps 0 and 1 are free starting points.
reach_two_back = 0 # reach(i - 2)
reach_one_back = 0 # reach(i - 1)
for i in range(2, len(cost) + 1):
# Arrive from step i - 1 (pay its cost, climb one) or from i - 2 (pay its cost, climb two).
reach = min(reach_one_back + cost[i - 1], reach_two_back + cost[i - 2])
reach_two_back = reach_one_back
reach_one_back = reach
return reach_one_back