leetcode 188. Best Time to Buy and Sell Stock IV
Posted thename
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode 188. Best Time to Buy and Sell Stock IV相关的知识,希望对你有一定的参考价值。
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的主要内容,如果未能解决你的问题,请参考以下文章
leetcode 188. Best Time to Buy and Sell Stock IV
[LeetCode] 188. Best Time to Buy and Sell Stock IV 买卖股票的最佳时间 IV
LeetCode 122, 123, 188. Best Time to Buy and Sell Stock II+III+IV
188. Best Time to Buy and Sell Stock IV