Best Time to Buy and Sell Stock IV -- leetcode
阿新 • • 發佈:2019-02-20
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討論:
該討論是針對交易次數為2次的的情況。
但思路是一樣的。我將其擴充到任意次數的情況。
需要注意的事,test case中,有一個非常大的k值,直接會讓記憶體分配失敗。
如何處理該種情況呢。 當k值超過prices值的個數時,此時,可以把問題轉換為交易數次不限的情況。即
Best Time to Buy and Sell Stock II
另一篇博文也很好的介紹了這個問題的解法。這兩者的思路其實是一樣的。