【leetcode】【股票问题】122 买卖股票的最佳时机 II

方法一 贪心算法(针对这道问题的特殊解法)

时间复杂度O(N)
首先要知道第0天买入,第3天卖出的利润:prices[3] - prices[0],相当于(prices[3] - prices[2]) + (prices[2] - prices[1]) + (prices[1] - prices[0])
那么根据prices可以得到每天的利润序列:(prices[i] - prices[i - 1])…(prices[1] - prices[0])。
可以发现,我们需要收集每天的正利润就可以,收集正利润的区间,就是股票买卖的区间,而我们只需要关注最终利润就可以了,不需要记录区间。
这就是贪心所贪的地方,只收集正利润。

class Solution {
    public int maxProfit(int[] prices) {
        int ben = 0;
        for ( int i = 0; i < prices.length - 1; i++){
            int diff = prices[i + 1] - prices[i];
            if (diff > 0){
                ben += diff;
            }
        }
        return ben;
    }
}

日期

2020-11-17

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值