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

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

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

import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        while (in.hasNextInt()) { // 注意 while 处理多个 case
            int a = in.nextInt();
            int b = in.nextInt();
            int[] prices = new int[a];
            for (int i = 0; i < a; i++) {
                prices[i] = in.nextInt();
            }
            int[][] data = new int[b+1][prices.length];
            for (int i = 1; i <= b; i++) {
                int max = 0;
                for (int j = 0; j < prices.length; j++) {
                    if (j == 0) {
                        max =  -prices[0];
                        data[i][0] = 0;
                    } else {
                        max = Math.max(max, data[i - 1][j - 1] - prices[j]);
                        data[i][j] = Math.max(data[i][j - 1], prices[j] + max );
                    }

                }
            }
            System.out.println(data[b][prices.length - 1]);
        }

    }
}

全部评论

相关推荐

07-02 13:52
武汉大学 golang
骗你的不露头也秒
牛客87776816...:😃查看图片
点赞 评论 收藏
分享
白火同学:大二有这水平很牛了,可以适当对关键信息加粗一点,比如关键技术、性能指标之类的。
点赞 评论 收藏
分享
06-18 13:28
已编辑
门头沟学院 Web前端
爱睡觉的冰箱哥:《给予你300的工资》,阴的没边了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务