122. 买卖股票的最佳时机 II(Java)

2024-01-03 01:31:38

题目描述:

给你一个整数数组 prices ,其中 prices[i] 表示某支股票第 i 天的价格。
在每一天,你可以决定是否购买和/或出售股票。你在任何时候 最多 只能持有 一股 股票。你也可以先购买,然后在 同一天 出售。
返回 你能获得的 最大 利润 。

输入:

prices = [7,1,5,3,6,4]

输出:

7
解释:在第 2 天(股票价格 = 1)的时候买入,在第 3 天(股票价格 = 5)的时候卖出, 这笔交易所能获得利润 = 5 - 1 = 4 。
随后,在第 4 天(股票价格 = 3)的时候买入,在第 5 天(股票价格 = 6)的时候卖出, 这笔交易所能获得利润 = 6 - 3 = 3 。
总利润为 4 + 3 = 7 。

代码实现:

public class Demo3 {
    public static void main(String[] args) {
        //案例
        int[] prices = new int[]{7, 1, 5, 3, 6, 4};
        System.out.println(maxProfit(prices));//7
    }

    public static int maxProfit(int[] prices) {
        //判断价格变化:找到部分升序求最值,部分降序则不管
        int fast = 0, slow = 0;//定义快慢指针
        //最大利润和
        int sum = 0;
        //当前利润
        int now = 0;
        //若数组中是乱序或者降序的情况
        for (int i = 0; i < prices.length; i++) {
            //快指针前进
            fast++;
            //防止索引越界
            if (fast < prices.length) {
                if (prices[fast] < prices[i]) {
                    //当fast指向元素比 之前部分元素小时,则计算这一部分元素的利润,累加到总利润
                    now = prices[fast - 1] - prices[slow];
                    //并让慢指针跟进
                    slow = fast;
                    //计算总利润
                    sum += now;
                }
            } else if (fast == prices.length) {
                //当最后一部分数据为升序时
                now = prices[fast - 1] - prices[slow];
                if (now > 0) {
                    //当前利润大于0,则累加
                    sum += now;
                }
            }
        }
        return sum;
    }
}

文章来源:https://blog.csdn.net/qq_61888137/article/details/135351988
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。