最小花费爬楼梯 dp

描述

给定一个整数数组 cost   ,其中 cost[i]  是从楼梯第i 个台阶向上爬需要支付的费用,下标从0开始。一旦你支付此费用,即可选择向上爬一个或者两个台阶。
你可以选择从下标为 0 或下标为 1 的台阶开始爬楼梯。
请你计算并返回达到楼梯顶部的最低花费。

数据范围:数组长度满足 1<= n <= 10^5,数组中的值满足 1\leqslant n\leqslant 10^4

输入描述:

第一行输入一个正整数 n ,表示数组 cost 的长度。

第二行输入 n 个正整数,表示数组 cost 的值。

输出描述:

输出最低花费

示例1

输入:

3

2 5 20

输出:

5

说明:你将从下标为1的台阶开始,支付5 ,向上爬两个台阶,到达楼梯顶部。总花费为5

示例2

输入:

10

1 100 1 1 1 90 1 1 80 1

输出:

6

说明:

你将从下标为 0 的台阶开始。

1.支付 1 ,向上爬两个台阶,到达下标为 2 的台阶。

2.支付 1 ,向上爬两个台阶,到达下标为 4 的台阶。

3.支付 1 ,向上爬两个台阶,到达下标为 6 的台阶。

4.支付 1 ,向上爬一个台阶,到达下标为 7 的台阶。

5.支付 1 ,向上爬两个台阶,到达下标为 9 的台阶。

6.支付 1 ,向上爬一个台阶,到达楼梯顶部。 总花费为 6 。

 代码:

import java.util.*;
import java.util.stream.Collectors;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        int n=Integer.parseInt(in.nextLine());
        List<Integer> list=Arrays.stream(in.nextLine().split(""))
            .map(Integer::parseInt).collect(Collectors.toList());

        int cost;
        List<Integer> minCosts=new ArrayList<>();
        for(int i=0;i<n;i++){
            if(i<2){
                minCosts.add(0);
            }else{
                int a=list.get(i-2)+minCosts.get(i-2);
                int b=list.get(i-1)+minCosts.get(i-1);
                if(a<=b){
                    minCosts.add(a);
                }else{
                    minCosts.add(b);
                }
            }
        }
        int x=list.get(n-2)+minCosts.get(n-2);
        int y=list.get(n-1)+minCosts.get(n-1);
        if(x<=y){
            cost=x;
        }else{
            cost=y;
        }
        System.out.println(cost);
    }
}

猜你喜欢

转载自blog.csdn.net/qq_43780761/article/details/126899517