Min Cost Climbing Stairs in Python

PythonServer Side ProgrammingProgramming

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 −


 Live Demo

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




Published on 04-Jul-2020 13:26:18