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).
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
Solution:
Using DP. Iinspired buy solution of Sell Stock III, we keep track the price and profit at current transaction.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public: | |
int maxProfit(int k, vector<int>& prices) { | |
int maxProfit=0; | |
if(prices.size()<2) | |
return 0; | |
if(k>prices.size()/2){ | |
for(int i=1; i<prices.size(); i++) | |
maxProfit += max(prices[i]-prices[i-1], 0); | |
return maxProfit; | |
} | |
int hold[k+1]; | |
int rele[k+1]; | |
for (int i=0;i<=k;++i){ | |
hold[i] = INT_MAX; | |
rele[i] = 0; | |
} | |
for(int i=0; i<prices.size(); i++){ | |
for(int j=k; j>=1; j--){ | |
rele[j] = max(rele[j], prices[i]-hold[j]); | |
hold[j] = min(hold[j], prices[i]-rele[j-1]); | |
maxProfit=max(maxProfit, rele[j]); | |
} | |
} | |
return maxProfit; | |
} | |
}; |
No comments:
Post a Comment