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).
Credits:
Special thanks to @Freezen for adding this problem and creating all test cases.
class Solution {
public:
int maxProfit(int k, vector<int> &prices) {
if (k >= prices.size())
return maxProfit2(prices);
vector<int> release(k+1);
vector<int> hold(k, INT_MIN);
for (auto p: prices) {
for (int i=0; i<k; i++) {
release[i] = max(release[i], hold[i]+p);
hold[i] = max(hold[i], release[i+1]-p);
}
}
return release[0];
}
int maxProfit2(vector<int> &prices) {
int profit = 0;
for (int i=0; i<(int)prices.size()-1; i++) {
if (prices[i+1] > prices[i])
profit += prices[i+1] - prices[i];
}
return profit;
}
};
此题思路借鉴之以下leetcode讨论:
https://leetcode.com/discuss/18330/is-it-best-solution-with-o-n-o-1
该讨论是针对交易次数为2次的的情况。
但思路是一样的。我将其扩充到任意次数的情况。
需要注意的事,test case中,有一个非常大的k值,直接会让内存分配失败。
如何处理该种情况呢。 当k值超过prices值的个数时,此时,可以把问题转换为交易数次不限的情况。即
Best Time to Buy and Sell Stock II
另一篇博文也很好的介绍了这个问题的解法。这两者的思路其实是一样的。
参见:http://blog.csdn.net/linhuanmars/article/details/23236995