码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode 188. Best Time to Buy and Sell Stock IV

时间:2019-10-02 12:58:58      阅读:62      评论:0      收藏:0      [点我收藏+]

标签:ret   pop   make   span   top   max   etc   element   solution   

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

标签:ret   pop   make   span   top   max   etc   element   solution   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!