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);
}
};