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.
Using local[i][j] means to reach the first day, the most local optimal solution of J transactions, with Global[i][j] to reach the first day, up to J times global optimal solution. The relationship between them is as follows (where diff = prices[i]–prices[i–1]):
LOCAL[I][J] = max (global[i–1][j–1], local[i–1][j] + diff)
GLOBAL[I][J] = max (Global[i–1][j], local[i][j])
The difference between local[i][j] and Global[i][j] is that local[i][j] means that there must be a trade (sell) on the first day, and when the price on day I is higher than the i-1 day (that is, diff > 0), Then it is possible to combine the transaction (sale of I-1 day) with the transaction of I-1 Day (sell) into a single transaction, that is, Local[i][j]=local[i-1][j]+diff, when the price of the first day is no higher than the i-1 day (i.e. diff<=0), So Local[i][j]=global[i-1][j-1]+diff, and because diff<=0, so can write local[i][j]=global[i-1][j-1]. GLOBAL[I][J] is the maximum amount of k transactions that we ask for in the previous I day, can be divided into two cases: if the day I do not have a trade (sell), then global[i][j]=global[i-1][j]; If there is a trade (sell) on the first day, then global[ I][J]=LOCAL[I][J].
//if (k >= days) go to II//K < days//local[0][0] = 0; global[0][0]//Local[i][j] = Math.max (Local[i-1][j] + differ, global[i-1][j-1]); On day I must trade diff >0//Global[i][j] = Math.max (Local[i][j], global[i-1][j]), trading on day I, or not trading Public classSolution { Public intMaxprofit (intKint[] prices) { if(Prices = =NULL|| Prices.length <= 1 | | k==0)return0; intDays =prices.length; if(k >= days)returnGetmaxprofit (prices);//question II intLocal[][] =New int[Days] [K+1]; intGlobal[][] =New int[Days] [K+1]; local[0][0] = 0; global[0][0] = 0; for(inti = 1; I < days; i++){ intdiff = prices[i]-prices[i-1]; for(intj = 1; J <= K; J + +) {Local[i][j]= Math.max (Local[i-1][j] + diff, Global[i-1][j-1]); GLOBAL[I][J]= Math.max (Local[i][j], global[i-1][j]); } } returnGlobal[days-1][k]; } Public intGetmaxprofit (int[] prices) { intTotal = 0; for(inti = 1; i < prices.length; i++){ if(Prices[i] > Prices[i-1]) Total + = Prices[i]-prices[i-1]; } returnTotal ; }}
188. Best time to Buy and Sell Stock IV