【LeetCode】122. 买卖股票的最佳时机 II - 贪婪算法

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

2023-8-10 10:29:32

没错,还是用双指针思想来套出来的。
感觉步骤很复杂,还调试了半天。

class Solution {
    public int maxProfit(int[] prices) {
        int pre = 0;
        int last = 1;
        int maxProfit = 0;
        int currentProfit = 0;
        while (last < prices.length) {
            if (prices[pre] >= prices[last] || prices[last] < prices[last - 1]) {
                maxProfit = maxProfit + currentProfit;
                currentProfit = 0;
                pre = last;
            } else {
                int temp = prices[last] - prices[pre];
                if (currentProfit < temp) {
                    currentProfit = temp;
                }
            }
            last++;
        }
        return maxProfit + currentProfit;
    }
}

贪婪算法:局部最优解就能够组成全局最优解

这道题呢,就是:计划在第N天买入,第N+1天卖出

最大利润就是:4 + 3 +1 = 8
在这里插入图片描述

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值