
- 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
Program to find to get minimum cost to climb at the top of stairs in Python?
Suppose we have a list of numbers called stairs and another value k. We are currently at stair 0 and want to climb to the last index of stairs. The value stair[i] indicates cost to reach at index and in each round we can either jump 1, 2, ... k, stairs at once. We have to find the minimum cost to climb to the last stair.
So, if the input is like stairs = [4, 11, 11, 3, 2] k = 3, then the output will be 9, as we use the stairs [4, 3, 2]
To solve this, we will follow these steps
q := a double ended queue and insert a pair (stairs[0], 0) into it
for i in range 1 to size of stairs, do
while i - q[0, 1] > k, do
remove item from left of q
curcost := q[0, 0] + stairs[i]
while q is not empty and and curcost <= first value of the last item of q, do
delete last element from q
insert (curcost, i) at the end of q
return first value of the last item of q
Let us see the following implementation to get better understanding
Example
from collections import deque class Solution: def solve(self, stairs, k): q = deque([(stairs[0], 0)]) for i in range(1, len(stairs)): while i - q[0][1] > k: q.popleft() curcost = q[0][0] + stairs[i] while q and curcost <= q[-1][0]: q.pop() q.append((curcost, i)) return q[-1][0] ob = Solution() stairs = [4, 11, 11, 3, 2] k = 3 print(ob.solve(stairs, k))
Input
[4, 11, 11, 3, 2], 3
Output
9
- Related Articles
- Program to find how many ways we can climb stairs in Python
- Program to find how many ways we can climb stairs (maximum steps at most k times) in Python
- Program to find minimum cost to merge stones in Python
- Program to Find Out the Minimum Cost to Purchase All in Python
- Program to find minimum cost to connect all points in Python
- Program to find minimum cost to cut a stick in Python
- Program to find minimum cost to hire k workers in Python
- Program to find minimum cost to reach final index with at most k steps in python
- Program to find minimum cost for painting houses in Python
- Program to find minimum deletion cost to avoid repeating letters 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?
- Program to Find Out the Minimum Cost Possible from Weighted Graph in Python
- Program to find minimum total cost for equalizing list elements in Python
- Program to find minimum cost to reduce a list into one integer in Python
- Program to find minimum cost to paint fences with k different colors in Python
