Loading Image

Friday, October 13, 2023

LeetCode Daily Challenges: 746. Min Cost Climbing Stairs


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


Example 1:
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.
Example 2:
Input: cost = [1,100,1,1,1,100,1,1,100,1]
Output: 6
Explanation: You will start at index 0.
- Pay 1 and climb two steps to reach index 2.
- Pay 1 and climb two steps to reach index 4.
- Pay 1 and climb two steps to reach index 6.
- Pay 1 and climb one step to reach index 7.
- Pay 1 and climb two steps to reach index 9.
- Pay 1 and climb one step to reach the top.
The total cost is 6.


Intuition:

The problem is about finding the minimum cost to reach the top of the staircase by either climbing one or two steps at a time. To solve this, we can use dynamic programming to keep track of the minimum cost to reach each step.


Approach:

  1. Initialize an array dp of the same length as the cost array to store the minimum cost for each step.
  2. Initialize dp[0] and dp[1] with the costs of the first two steps, as you can start from either step 0 or step 1.
  3. Iterate through the array starting from step 2 and for each step i, update dp[i] as the minimum of the cost to reach step i-1 plus the cost of step i and the cost to reach step i-2 plus the cost of step i. This ensures that you choose the minimum cost path to reach the current step.
  4. After iterating through all the steps, the minimum cost to reach the top of the staircase is the minimum of the last two elements in the dp array.

Complexity:

Time complexity: The algorithm iterates through the cost array once, so the time complexity is O(n), where n is the number of steps in the staircase.

Space complexity: We use an additional array dp of the same length as the cost array, so the space complexity is O(n) to store the dynamic programming table. 


Code Snapshot:




No comments:

Post a Comment