Description:
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.
Dynamic planning, Recursive: reference: http://blog.csdn.net/feliciafay/article/details/45128771
Local[i][j]=max (Global[i-1][j-1]+max (diff,0), Local[i-1][j]+diff),
Global[i][j]=max (Local[i][j],global[i-1][j])
Public classSolution { Public intMaxprofit (intKint[] prices) { intLen =prices.length; if(Len < 2) { return0; } if(k >Len) { returnBigprofit (prices); } int[] Local =New int[K+1]; int[] Global =New int[K+1]; Arrays.fill (Local,0); Arrays.fill (Global,0); for(inti=0; i<len-1; i++) { intdiff = prices[i+1]-Prices[i]; for(intJ=k; j>=1; j--) {Local[j]= Math.max (global[j-1]+ (diff>0?diff:0), local[j]+diff); GLOBAL[J]=Math.max (Global[j], local[j]); } } returnGlobal[k]; } Public intBigprofit (int[] prices) { intres = 0; for(inti=0; i<prices.length-1; i++) { if(Prices[i] < prices[i+1]) {res+ = prices[i+1]-Prices[i]; } } returnRes; } }
Leetcode--best time to Buy and Sell Stock IV