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.
Analyse: Assume global[i][j] represents the maximum profit at day i with j transactions, local [i][j] is the maximum profit at day i with j transactions at the last transaction occurred on day i. Then we have: global[i][j] = max(local[i][j], global[i - 1][j]) (the left one is doing the transaction at day i while the right one is not doing the transaction at day i), local[i][j] = max(local[i - 1][j] + diff, global[i - 1][j - 1] + max(0, diff)). (we have to do the j-th transaction on day i, so if we already did j transactions at day i - 1 and did the last transaction on the (i - 1)th day, or we did j - 1 transactions by the (i - 1)th day, then we choose the larger one.
Runtime: 8ms.
1 class Solution { 2 public: 3 int maxProfit(int k, vector<int>& prices) { 4 if(prices.size() <= 1 || k == 0) return 0; 5 6 int result = 0; 7 if(k >= prices.size()){//cannot do k transactions, then do all operations which can earn money 8 for(int i = 1; i < prices.size(); i++){ 9 if(prices[i] > prices[i - 1]) 10 result += prices[i] - prices[i - 1]; 11 } 12 return result; 13 } 14 15 const int n = k + 1; 16 int l[n] = {0}, g[n] = {0}; 17 18 for(int i = 0; i < prices.size() - 1; i++){ 19 int diff = prices[i + 1] - prices[i]; 20 for(int j = k; j >= 1; j--){ 21 l[j] = max(g[j - 1] + max(0, diff), l[j] + diff); 22 g[j] = max(l[j], g[j]); 23 } 24 } 25 return g[k]; 26 } 27 };