EasyNo. 0746

Min Cost Climbing Stairs — LeetCode 746 Python Solution

Topics
Array, Dynamic Programming
On study lists
NeetCode 150 and LeetCode 75
Reading time
2 min

The 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.

Example

Input
cost = [10,15,20]
Output
15
Explanation
You will start at index 1.

Python solution

PythonSolution
class Solution:
    def minCostClimbingStairs(self, cost: List[int]) -> int:
        @cache
        def dfs(i: int) -> int:
            if i >= len(cost):
                return 0
            return cost[i] + min(dfs(i + 1), dfs(i + 2))

        return min(dfs(0), dfs(1))

Complexity

Time
O(n)
Space · auxiliary
O(n)where n is the length of the array cost

Pattern: Dynamic Programming

Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 746. Min Cost Climbing Stairs is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Dynamic Programming.

The dynamic programming guide has the Python template for the pattern and the 481 LeetCode problems that use it.

Related problems

Related problems
No.ProblemDifficulty
0741Cherry PickupHard
0045Jump Game IIMedium
0053Maximum SubarrayMedium
0055Jump GameMedium
0063Unique Paths IIMedium
0064Minimum Path SumMedium

Frequently asked questions

How hard is LeetCode 746. Min Cost Climbing Stairs?

LeetCode 746. Min Cost Climbing Stairs is rated Easy on LeetCode.

What is the time complexity of LeetCode 746. Min Cost Climbing Stairs?

The Python solution on this page runs in O(n).

What is the space complexity of LeetCode 746. Min Cost Climbing Stairs?

The Python solution on this page uses O(n), where n is the length of the array \textit{cost} auxiliary space.

What topics does LeetCode 746. Min Cost Climbing Stairs cover?

LeetCode 746. Min Cost Climbing Stairs is tagged Array and Dynamic Programming on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.