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.
Analyse:assume Global[i][j] represents the maximum profit at day I with J transactions, Local [I][j] is the maximum ProFi T at day I with J transactions at the last transaction occurred in Day I. Then we had: global[i][j] = max (Local[i][j], global[i-1][j]) (the left one was doing the transaction at day I W Hile the right one isn't 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 does the j-th transaction on day I, so if we already did J transactions at day I-1 and does the last Transactio N on the (i-1) th day, or we do j-1 transactions by the (i-1) th day, then we choose the larger one.
Runtime:8ms.
1 classSolution {2 Public:3 intMaxprofit (intK, vector<int>&prices) {4 if(Prices.size () <=1|| K = =0)return 0;5 6 intresult =0;7 if(k >= prices.size ()) {//cannot do k transactions, then does all operations which can earn money8 for(inti =1; I < prices.size (); i++){9 if(Prices[i] > Prices[i-1])TenResult + = Prices[i]-prices[i-1]; One } A returnresult; - } - the Const intn = k +1; - intL[n] = {0}, G[n] = {0}; - - for(inti =0; I < prices.size ()-1; i++){ + intdiff = prices[i +1] -Prices[i]; - for(intj = k; J >=1; j--){ +L[J] = max (G[j-1] + MAX (0, diff), L[j] +diff); AG[J] =Max (L[j], g[j]); at } - } - returnG[k]; - } -};
best time to Buy and Sell Stock iv****