leetcode 122. Best Time to Buy and Sell Stock II

题目122. Best Time to Buy and Sell Stock II
标签: 贪心

思路

找到除了第一个点的所有峰值,然后,对于每一个峰值,减去与前一个峰值(包括第一个点,如果它也是峰值的话)之间的山谷值得到差值,将所有的差值加起来就是最大收益

实现

# include <iostream>
# include <vector>

using namespace std;


class Solution {
public:
    int maxProfit(vector<int>& prices) {
       int size = prices.size();
       if(size <= 1) return 0;
       int ret = 0;
       int last_max = -1, last_min = prices[0];
       for(int i = 1; i < size; i++) {
            if(prices[i] <= last_min && last_max == -1) last_min = prices[i];
            else if(prices[i] > last_min && prices[i] >= last_max) last_max = prices[i];
            else { // get a valid and best last_min and last_max
                ret += last_max - last_min;
                last_min = prices[i];
                last_max = -1;          
            }
        }
        // the last case
        if(last_max != -1) ret += last_max - last_min;
        return ret;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值