首页 > 其他 > 详细

leetcode 188. Best Time to Buy and Sell Stock IV

时间:2019-10-02 13:27:23      阅读:102      评论:0      收藏:0      [点我收藏+]
class Solution {
public:
    int maxProfit(int k, vector<int> &prices){
        int n=prices.size(),v=0,p=0,ret=0;
        vector<int> profits;
        stack<pair<int,int>> vp;
        while(p<n){
            for(v=p;v<n-1&&prices[v]>=prices[v+1];++v);
            for(p=v+1;p<n&&prices[p]>=prices[p-1];++p);
            while(!vp.empty()&&prices[v]<prices[vp.top().first]){
                profits.push_back(prices[vp.top().second-1]-prices[vp.top().first]);
                vp.pop();
            }
            while(!vp.empty()&&prices[p-1]>=prices[vp.top().second-1]){
                profits.push_back(prices[vp.top().second-1]-prices[v]);
                v=vp.top().first;
                vp.pop();
            }
            vp.push(make_pair(v,p));
        }
        while(!vp.empty()){
            profits.push_back(prices[vp.top().second-1]-prices[vp.top().first]);
            vp.pop();
        }
        if(k>=profits.size()) return accumulate(profits.begin(),profits.end(),0);
        nth_element(profits.begin(),profits.end()-k,profits.end());
        return accumulate(profits.end()-k,profits.end(),0);
    } 
};

 

leetcode 188. Best Time to Buy and Sell Stock IV

原文:https://www.cnblogs.com/TheName/p/11617083.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!