# 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

Live Demo

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