PIXELBANKv8.2.1
Menu

Min Cost Climbing Stairs

Given an array cost where cost[i] is the cost of the ith step, you can start from step 0 or 1. Each step you can climb 1 or 2 steps. Return the minimum cost to reach the top (past the last step).

Example:

Input:
10,15,20
Output:
15
Reasoning:
  • We start by initializing an array dp where dp[i] represents the minimum cost to reach the ith step. For the given input, cost = [10, 15, 20], we have dp[0] = 10 and dp[1] = 15.
  • Then, we fill up the dp array by iterating through the cost array. For each step i, we calculate dp[i] = min(dp[i-1], dp[i-2]) + cost[i]. So, dp[2] = min(dp[1], dp[0]) + cost[2] = min(15, 10) + 20 = 10 + 20 = 30.
  • However, since we can start from step 0 or 1 and climb 1 or 2 steps, we consider the minimum cost to reach the top as min(dp[n-1], dp[n-2]), where n is the number of steps. In this case, min(dp[2], dp[1]) = min(30, 15) = 15.
  • The final output is the minimum cost to reach the top, which is 1515.

Constraints:

  • 2 <= len(cost) <= 1000
  • 0 <= cost[i] <= 999
Editor

Test Results

0/0
Run code to see test results.