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).
Feel this problem is too difficult, because the request can only be traded, so in consideration of peaks, trough the basis to consider the number of transactions, on-line only found the C + + version, run a bit, can run correctly.
classSolution { Public: intMaxprofit (intK, vector<int> &prices) { if(Prices.empty () | | k = =0) return 0; if(k >=prices.size ())returnSolvemaxprofit (prices); Vector<int>Global(k +1,0); Vector<int> local (k +1,0); for(inti =1; I < prices.size (); i++) { 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]); } } return Global[K]; } Private: intSolvemaxprofit (vector<int> &prices) { intres =0; for(inti =1; I < prices.size (); i++) { intdiff = prices[i]-prices[i-1]; if(diff >0) Res+=diff; } returnRes; } };
best time to Buy and Sell Stock IV