随笔都是学习笔记
随笔仅供参考,为避免笔记中可能出现的错误误导他人,请勿转载。
posts - 398,comments - 0,views - 13万
复制代码
package Demo_1_20_;

/*
* 描述
假设你有一个数组prices,长度为n,其中prices[i]是股票在第i天的价格,请根据这个价格数组,返回买卖股票能获得的最大收益
1.你可以买入一次股票和卖出一次股票,并非每天都可以买入或卖出一次,总共只能买入和卖出一次,且买入必须在卖出的前面的某一天
2.如果不能获取到任何利润,请返回0
3.假设买入卖出均无手续费

要求:空间复杂度 O(1)O(1),时间复杂度 O(n)O(n)
    示例1
        输入:[8,9,2,5,4,7,1]

        返回值:5

    说明:
        在第3天(股票价格 = 2)的时候买入,在第6天(股票价格 = 7)的时候卖出,最大利润 = 7-2 = 5 ,不能选择在第2天买入,第3天卖出,这样就亏损7了;同时,你也不能在买入前卖出股票。
        示例2
        输入:[2,4,1]

        返回值:2

    示例3
        输入:[3,2,1]

        返回值:0
* */

public class naib {
    public static void main(String[] args) {
        int [] a = new int[]{3,2,5,7,8,13,3,1};  // 股票不同日期的价格
        int b = maxProfit(a);  // b就是返回值,也可以写成System.out.println(maxProfit(a));
        System.out.println(b);
    }
    public static int maxProfit (int[] prices) {
        int min = prices[0];    // 最小价格
        int max = prices[0];    // 最大价格
        int profit;             // 利润
        int index_min = 0;  // 记录最小值的日期
        int index_max = 0;  // 记录最大值的日期
        for(int x = 0; x < prices.length - 1; x++){ // 最后一天肯定不能买入咯,否则怎么卖
            if (min >= prices[x])   // 最小值当然不能比其它值大咯
            {
                min = prices[x];    // 最小值大于一个数,那么最小值就是那个数
                index_min = x;
            }if (max <= prices[x + 1]){
                max = prices[x + 1];    // 最大值小于一个数,那么最大值就是那个数
                index_max = x + 1;
            }if (index_max < index_min){    // 卖出的日期肯定不能在买入前啊
                max = prices[index_min];    // 如果在买入的日期后,股票价格都小于买入价格,那么卖出价格最大就应该是买入价格咯
            }
        }
        profit = max - min;     // 利润自然是最大减最小
        return profit;
    }
}

复制代码

 

 

 

 

经供参考

 

posted on   时间完全不够用啊  阅读(434)  评论(0编辑  收藏  举报
(评论功能已被禁用)
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示