随笔都是学习笔记
随笔仅供参考,为避免笔记中可能出现的错误误导他人,请勿转载。
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 2022-01-21 15:38  时间完全不够用啊  阅读(450)  评论(0)    收藏  举报