Min Cost Climbing Stairs

On a staircase, the i-th step has some non-negative cost cost[i] assigned (0 indexed).
Once you pay the cost, you can either climb one or two steps. You need to find the minimum cost to reach the top of the floor, and you can either start from the step with index 0, or the step with index 1.

Example 1:

Input: cost ={10, 15, 20}
Output: 15

Approach

Java

public class MinCostClimbingStairs {
    public static void main(String[] args) {
        int[] cost = { 101520 };
        System.out.println(minCostClimbingStairs(cost));
    }

    static int minCostClimbingStairs(int[] cost) {
        int n = cost.length;
        int dp[] = new int[n + 1];
        dp[0] = cost[0];
        dp[1] = cost[1];
        for (int i = 2; i <= n; i++) {
            // if we are at last position
            if (i == n)
                dp[i] = Math.min(dp[i - 1], dp[i - 2]);

            // else
            else
                dp[i] = Math.min(dp[i - 1], dp[i - 2]) + cost[i];
        }
        return dp[n];
    }
}

C++

#include <bits/stdc++.h>
using namespace std;

int minCostClimbingStairs(vector<int>& cost)
{
        int n=cost.size();
        int dp[n+1];
        dp[0]=cost[0];
        dp[1]=cost[1];
        for(int i=2;i<=n;i++)
        {
            //if we are at last position
            if(i==n)
                  dp[i]=min(dp[i-1],dp[i-2]);

          //else
            else
                dp[i]=min(dp[i-1],dp[i-2])+cost[i];
        }
        return dp[n];
}
int main()
{
    vector<intcost ={101520};
    cout<<minCostClimbingStairs(cost);
    return 0;
}



No comments:

Post a Comment