Min Cost Climbing Stairs#

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.

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.

from typing import List
class Solution:
    def minCostClimbingStairs(self, cost: List[int]) -> int:
        pass
import math
from typing import List
class Solution:
    def minCostClimbingStairs(self, cost: List[int]) -> int:
        n = len(cost)
        steps = [1,2]
        if n == 0:
            return 0
        def minCostClimbingStairsRec(cost, currentIndex):
            if currentIndex >= n:
                return 0
            stepCosts = []
            for s in steps:
                stepCosts.append(minCostClimbingStairsRec(cost, currentIndex+s))
            return cost[currentIndex] + min(stepCosts)
            
        return min(minCostClimbingStairsRec(cost, 0), minCostClimbingStairsRec(cost, 1))
x = Solution()
x.minCostClimbingStairs([10,15,20])
15
import math
from typing import List
class Solution:
    def minCostClimbingStairs(self, cost: List[int]) -> int:
        n = len(cost)
        steps = [1,2]
        if n == 0:
            return 0
        dp = [0 for _ in range(len(cost)+1)]
        def minCostClimbingStairsRec(cost, currentIndex):
            if currentIndex >= n:
                return 0
            if dp[currentIndex] != 0:
                return dp[currentIndex]
            stepCosts = []
            for s in steps:
                stepCosts.append(minCostClimbingStairsRec(cost, currentIndex+s))
            dp[currentIndex] = cost[currentIndex] + min(stepCosts)
            return dp[currentIndex]
            
        return min(minCostClimbingStairsRec(cost, 0), minCostClimbingStairsRec(cost, 1))
x = Solution()
x.minCostClimbingStairs([10,15,20])
15
import math
from typing import List
class Solution:
    def minCostClimbingStairs(self, cost: List[int]) -> int:
        n = len(cost)
        dp = []
        for i in range(n):
            if i < 2: 
                dp.append(cost[i])
            else:
                dp.append(cost[i]+min(dp[i-1], dp[i-2]))
            
        return min(dp[n-1],dp[n-2])
x = Solution()
x.minCostClimbingStairs([1,100,1,1,1,100,1,1,100,1])
6

return min(dp[n-1],dp[n-2]) -> this is the catch