您的位置:首页 > 其它

Best Time to Buy and Sell Stock IV

2015-11-28 22:06 295 查看
Say you have an array for which the ith element is the price of a given stock on day i.

Design an algorithm to find the maximum profit. You may complete at most k transactions.

Note:

You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

class Solution {
public:
int maxProfit(int k, vector<int>& prices) {
int n=prices.size();
if(k==0||n<2) return 0;
if(k>n/2){
int res=0;
for(int i=1;i<n;i++){
if(prices[i]-prices[i-1]>0){
res+=prices[i]-prices[i-1];
}
}
return res;
}
vector<int>buy(k,INT_MIN);
vector<int>sell(k,0);
for(int i=0;i<n;i++){
buy[0]=max(buy[0],-prices[i]);
sell[0]=max(sell[0],buy[0]+prices[i]);
for(int j=1;j<k;j++){
buy[j]=max(buy[j],sell[j-1]-prices[i]);
sell[j]=max(sell[j],buy[j]+prices[i]);
}
}
return sell[k-1];
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: