#3693
Climbing Stairs II
MediumArrayDynamic ProgrammingDynamic ProgrammingGreedy Algorithms
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
Using dynamic programming, we can store the minimum cost to reach each step, building on previously computed results. This avoids redundant calculations and significantly reduces time complexity.
⚙️
Algorithm
3 steps- 1Step 1: Initialize a dp array of size n+1 with dp[0] = 0 and others as infinity.
- 2Step 2: Iterate through each step i from 0 to n, updating dp[j] for j = i+1, i+2, i+3 based on the cost formula.
- 3Step 3: Return dp[n] as the minimum cost to reach the last step.
solution.py8 lines
1def minCost(n, costs):
2 dp = [float('inf')] * (n + 1)
3 dp[0] = 0
4 for i in range(n):
5 for j in range(1, 4):
6 if i + j <= n:
7 dp[i + j] = min(dp[i + j], costs[i] + j * j + dp[i])
8 return dp[n]ℹ
Complexity note: We compute each step's cost once, leading to linear time complexity.
- 1Dynamic programming reduces redundant calculations.
- 2Understanding cost transitions is crucial.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.