- Related Questions & Answers
- 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 Out the Minimum Cost to Purchase All in Python
- Program to find minimum cost to reach final index with at most k steps in python
- Min Cost Climbing Stairs in Python
- 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 the minimum cost to arrange the numbers in ascending or descending order 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
- Program to find minimum cost to pick up gold in given two locations in Python
- Find minimum adjustment cost of an array in Python
- Find the minimum cost to reach destination using a train
- Find minimum cost to buy all books in C++
- Program to find minimum cost to increase heights of trees where no adjacent tree has same height in Python

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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

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))

[4, 11, 11, 3, 2], 3

9

Advertisements