Anusha Murali

Logo

Please see github.com/anusha-murali for all of my repositories.

View GitHub Profile

Minimum Cost of Climbing Stairs

Problem: You are given an integer array cost where cost[i] is the cost of ith step on a staircase. Once you pay the cost, you can either climb one or two steps.

You can either start from the step with index 0, or the step with index 1.

Return the minimum cost to reach the top of the floor.

Example 1:

Input: cost = [10,15,20]; Output: 15

Explanation: You will start at index 1. Pay 15 and climb two steps to reach the top. The total cost is 15.

Example 2:

Input: cost = [1,100,1,1,1,100,1,1,100,1]; Output: 6

stairs

Explanation: You will start at index 0.

Solution 1 Recursion

Let minCost(n) be the minimum cost to reach stair $n$.

Hence minCost(n) = cost(n) + min(minCost(n-1), minCost(n-2)).

Hence, we have the following recursive solution:

def minCost(n):
  if n < 2:
    return cost[n]
  return cost[n] + min(minCost(n-1), minCost(n-2))

Therefore, if the size of cost = $n$, we can find the minimum cost to reach the top of the stairs using:

min(minCost(n-1), minCost(n-2))

Solution 2 Dynamic Programming

The recursive solution above suffers from repeated recomuptation of the minimum costs. We can memoize the minimum cost to climb stair $i$ in an array and avoid the repeated recomputation of the minimum costs as follows:

def minCostClimbingStairs(cost):
    dp = [0]*(len(cost))

    for i in range(len(cost)):
        dp[i] = cost[i] + min(dp[i-1],dp[i-2])

    return min(dp[len(cost)-1], dp[len(cost)-2])

Runtime: Unlike Solution 1, the memoized version above solves each subproblem only once. Since there are only $n-1$ additions, the runtime is $O(n)$.

Back to Dynamic Programming Problems


anusha-murali.github.io