
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Min Cost Climbing Stairs in Python
Suppose there is a staircase, here the i-th step will be some non-negative cost value cost[i] assigned. When we pay the cost, we can either climb one or two steps. We have to find minimum cost to reach the top of the floor, and we also can either start from the step with index 0, or the step with index 1.
So, if the input is like cost = [12,17,20], then the output will be 17, The cheapest position to start from step 1 as we have to pay that cost and go to the top.
To solve this, we will follow these steps −
- dp := an array of size same as cost, and fill with 0
- dp[0] := cost[0]
- if size of cost >= 2, then
- dp[1] := cost[1]
- for i in range 2 to size of cost - 1, do
- dp[i] := cost[i] + minimum of dp[i-1], dp[i-2]
- return minimum of dp[-1], dp[-2]
Let us see the following implementation to get better understanding −
Example
class Solution: def minCostClimbingStairs(self, cost): dp = [0] * len(cost) dp[0] = cost[0] if len(cost) >= 2: dp[1] = cost[1] for i in range(2, len(cost)): dp[i] = cost[i] + min(dp[i-1], dp[i-2]) return min(dp[-1], dp[-2]) ob = Solution() print(ob.minCostClimbingStairs([12,17,20]))
Input
[12,17,20]
Output
17
- Related Articles
- Climbing Stairs in C++
- How to implement backtracking for a climbing stairs practice in JavaScript?
- Python Program for Min Cost Path
- Min Cost Path
- Program to find to get minimum cost to climb at the top of stairs in Python?
- Min Stack in Python
- max() and min() in Python
- Program to find how many ways we can climb stairs in Python
- Use of min() and max() in Python
- Find Min-Max in heterogeneous list in Python
- Reena climbs up five stairs every second and than climb down two stairs over the next second .how many seconds will she take to climb 60 stairs?
- List Methods in Python - in, not in, len(), min(), max()
- Program to fill Min-max game tree in Python
- Program to find maximum subarray min-product in Python
- Program to find number of ways we can reach to the next floor using stairs in Python

Advertisements