Minimum Cost Climbing Stairs

Minimum Cost to Climb Stairs

You are given an array of integers, `cost`, where `cost[i]` represents the cost of stepping from the (i)th floor of a staircase. After paying the cost, you can move to either the (i+1)th floor or the (i+2)th floor.

You can start at either the 0th or the 1st floor.

Your task is to determine the minimum cost required to reach the top of the staircase, which is just beyond the last floor in the `cost` array.

minimum cost climbing stairs problem

Explanation: We can start at index = 1 and pay the cost of cost[1] = 2 and take two steps to reach the top. The total cost is 2.

Constraints:

  • 2 <= cost.length <= 100
  • 0 <= cost[i] <= 100

Minimum Cost Climbing Stairs Solution

There are mainly 4 approach to solve this problem:

  1. Recursion Method
  2. Dynamic Programming – Top Down
  3. Dynamic Programming – Bottom Up
  4. Dynamic Programming – Space Optimized

1. Recursion Method

Solve the problem by breaking it into smaller sub problems and calculating the cost recursively for each possible step. This approach is simple but can be slow due to repeated calculations.

  • Time complexity: O(2^n)
  • Space complexity: O(n)

Code

2. Dynamic programming Top Down Method

Use recursion with memorization to store results of previously solved sub problems, avoiding redundant calculations and improving efficiency.

  • Time complexity: O(n)
  • Space complexity: O(n)

Code

3. Dynamic Programming Bottom Up Method

Build the solution iteratively from the smallest sub problem to the full problem, calculating costs step by step and storing them in an array.

  • Time complexity: O(n)
  • Space complexity: O(n)

Code

4. Dynamic programming Space Optimized Method

Improve the Bottom-Up approach by using only two variables instead of an entire array, reducing space usage while still computing the minimum cost.

  • Time complexity: O(n)
  • Space complexity: O(1)

Code

More Articles