best time to Buy and Sell Stock IV
Say you has an array for which the i-th element is the price of a given-stock on day I.
Design an algorithm to find the maximum profit. Transactions at the most K.
Note:
Engage in multiple transactions on 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.
The difficulty of this problem is obviously increased. It is the combination of the best time to buy and Sell Stock II and the best time to buy and Sell Stock III two questions.
Refer to the blog post, mainly two recursive formulas.
1 Global 1 0 )); 2 Global [j] = max (global[j], Local[j]);
1 classSolution {2 Public:3 intMaxprofit (intK, vector<int>&prices) {4 intresult;5 inttotal_times=0;6 intProfit_max =0;7 for(intI=1; I<prices.size (); i++)8 {9 intdiff = prices[i]-prices[i-1];Ten if(diff>0) One { AProfit_max + =diff; - if((I<prices.size ()-1) && (prices[i+1]-prices[i]<=0))|| (I==prices.size ()-1)) - { thetotal_times++; - } - } - } + if(K>=total_times)returnProfit_max; -vector<int> local (k +1,0); +vector<int>Global(k +1,0); A for(inti =1; I < prices.size (); i++) at { - intdiff = prices[i]-prices[i-1]; - for(intj = k; J >=1; j--) { -LOCAL[J] = max (local[j] + diff,Global[J-1] + Max (diff,0)); - Global[j] = max (Global[j], Local[j]); - } in } - return Global[K]; to } +};
[Leetcode] best time to Buy and Sell Stock IV