题解 | #买卖股票的最好时机(二)#

买卖股票的最好时机(二)

https://www.nowcoder.com/practice/fbc5dad3e215457fb82a3ae688eb7281

import java.util.Scanner;

public class Main {

    public static int solution(int[] prices) {
        int buy = 0;
        int res = 0;
        for (int i = 1; i < prices.length; i++) {
            // 只要下降,就在前一天卖出,且当天买入
            if (prices[i] < prices[i - 1]) {
                // 不是连续下降的场景
                if (buy != i - 1) {
                    res += prices[i - 1] - prices[buy];
                }
                buy = i;
            }
        }
        // 边界处理
        if (buy != prices.length - 1) {
            res += prices[prices.length - 1] - prices[buy];
        }
        return res;
    }




    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        int[] prices = new int[n];
        for (int i = 0; i < prices.length; i++) {
            prices[i] = in.nextInt();
        }
        System.out.println(solution(prices));
    }
}

全部评论

相关推荐

02-05 08:49
已编辑
武汉大学 Java
野猪不是猪🐗:36k和36k之间亦有差距,ms的36k和pdd的36k不是一个概念
点赞 评论 收藏
分享
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务