您的位置:首页 > 其它

[leetcode] Best Time to Buy and Sell Stock IV

2015-03-15 10:57 405 查看

Best Time to Buy and Sell Stock IV

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).

题解:

参考/article/4901626.html/article/1378264.html

class Solution {
public:
int solvemaxProfit(vector<int> prices) {
int profit = 0;
for(int i=0;i<prices.size()-1;i++) {
if(prices[i+1]>prices[i])
profit += prices[i+1]-prices[i];
}
return profit;
}
int maxProfit(int k, vector<int> &prices) {
int n = prices.size();
if(n<=0)
return 0;
if(k>=n)
return solvemaxProfit(prices);
int global[k+1] = {0};
int local [k+1] = {0};
for(int i=0;i<n-1;i++) {
int tmp = prices[i+1]-prices[i];
for(int j=k;j>=1;j--) {
local[j]  = max(global[j-1]+max(tmp, 0), local[j]+tmp);
global[j] = max(local[j], global[j]);
}
}
return global[k];
}
};


View Code
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: