leecode第一百二十一题(买卖股票的最佳时机II)

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int len=prices.size();
        if(len<=0)
            return 0;
        
        int sta=0,lirun=0;
        while(sta<len-1)
        {
            while(sta<len-2 && prices[sta]>prices[sta+1])//找到当前第一个最小值
                sta++;
            if(sta==len-2 && prices[sta]>prices[sta+1])
                return lirun;
            
            int max_num=sta+1;
            while(max_num<len-2 && prices[max_num]<prices[max_num+1])//找到第一个最小值后的第一个不小于后面的值
                max_num++;
            if(max_num==len-2 && prices[max_num]<prices[max_num+1])
                max_num++;
            
            lirun=lirun+prices[max_num]-prices[sta];//我们认为最近的利润是当前第一个最小值和第一个不输第二天的值的差,而这种利润的和不会少于全局唯一最大利润
            sta=max_num+1;
        }
        
        return lirun;
    }
};

分析:

思路有,但是一开始不确认正不正确,但是举的例子告诉我这样想目前是对的,于是就写了。

值的注意的是,while(max_num<len-2 && prices[max_num]<prices[max_num+1]),这句话里以后一定要先把值的边界性判断放前面,不然max_num+1超出边界,会提示错误。

猜你喜欢

转载自www.cnblogs.com/CJT-blog/p/10641841.html
今日推荐