#746

Min Cost Climbing Stairs

Easy
ArrayDynamic ProgrammingDynamic ProgrammingArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(n)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal solution uses dynamic programming to build up the minimum costs from the bottom of the stairs to the top, ensuring that we only calculate each step once. This is efficient and avoids redundant calculations.

⚙️

Algorithm

4 steps
  1. 1Step 1: Create a dp array where dp[i] represents the minimum cost to reach step i.
  2. 2Step 2: Initialize dp[0] and dp[1] with the costs of the first two steps.
  3. 3Step 3: Iterate from step 2 to the last step, calculating dp[i] as the cost of step i plus the minimum of dp[i-1] and dp[i-2].
  4. 4Step 4: The result is the minimum of dp[n-1] and dp[n-2], where n is the length of the cost array.
solution.py9 lines
1# Full working Python code
2
3def minCost(cost):
4    n = len(cost)
5    dp = [0] * (n + 1)
6    dp[0], dp[1] = cost[0], cost[1]
7    for i in range(2, n):
8        dp[i] = cost[i] + min(dp[i - 1], dp[i - 2])
9    return min(dp[n - 1], dp[n - 2])

Complexity note: The time complexity is O(n) because we only loop through the cost array once. The space complexity is O(n) due to the dp array storing the minimum costs.

  • 1Dynamic programming is a powerful technique for optimizing recursive solutions by storing intermediate results.
  • 2Understanding the problem as a pathfinding issue helps in visualizing the solution.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.