📘
Min Cost Climbing Stairs
Given an array cost where cost[i] is the cost of the ith step, you can start from step 0 or 1. Each step you can climb 1 or 2 steps. Return the minimum cost to reach the top (past the last step).
Example:
Input:
10,15,20
Output:
15
Reasoning:
- We start by initializing an array
dpwheredp[i]represents the minimum cost to reach the ith step. For the given input,cost = [10, 15, 20], we havedp[0] = 10anddp[1] = 15. - Then, we fill up the
dparray by iterating through thecostarray. For each stepi, we calculatedp[i] = min(dp[i-1], dp[i-2]) + cost[i]. So,dp[2] = min(dp[1], dp[0]) + cost[2] = min(15, 10) + 20 = 10 + 20 = 30. - However, since we can start from step 0 or 1 and climb 1 or 2 steps, we consider the minimum cost to reach the top as
min(dp[n-1], dp[n-2]), wherenis the number of steps. In this case,min(dp[2], dp[1]) = min(30, 15) = 15. - The final output is the minimum cost to reach the top, which is 15.
Constraints:
- 2 <= len(cost) <= 1000
- 0 <= cost[i] <= 999
Editor
Python 3.13.1
Test Results
0/0Run code to see test results.