LeetCode : Best Time to Buy and Sell Stock

一串数字根据大小看成高低起伏的序列。用后面的峰值减去前面的谷值可以得到最大差值。

int Solution::maxProfit(vector<int>& prices)
{
    if(prices.size() < 2)
        return 0;

    int min_index = 0, max_index = 0;
    int min = prices[0];
    int res = 0;

    while(min_index < prices.size() && max_index < prices.size())
    {
        // 找到新的谷值
        min_index = max_index;
        while(min_index + 1 < prices.size() && prices[min_index] >= prices[min_index + 1])
            min_index++;

        // 和旧谷值比较,记录小的那个
        min = min(min, prices[min_index]);

        // 找到新谷值后面的峰值
        max_index = min_index + 1;
        while(max_index + 1 < prices.size() && prices[max_index] <= prices[max_index + 1])
            max_index++;

        //峰值 - 最小谷值 = 最大差值
        if(max_index < prices.size())
            res = max(res, prices[max_index] - min);
    }

    return res;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值