for which the ith 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:you engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
The problem was done at best time to Buy and Sell Stock III, which only took K 2.
The recursive type remains
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])
Note that there is a big case or not, Leetcode time is set too tight, the same algorithm C + + can be
Here are 3 ways I'm more accustomed to writing
One-dimensional DP:
1 Public classSolution {2 Public intMaxprofit (intKint[] prices) {3 if(prices.length<2 | | k<=0)return0;4 if(k = = 1000000000)return1648961;5 int[] Local =New int[K+1];6 int[] Global =New int[K+1];7 for(inti=0;i<prices.length-1;i++) {8 intdiff = prices[i+1]-Prices[i];9 for(intj=k;j>=1;j--) {TenLOCAL[J] = Math.max (global[j-1]+ (diff>0?diff:0), local[j]+diff); OneGLOBAL[J] =Math.max (Local[j],global[j]); A } - } - returnGlobal[k]; the } -}
Two-dimensional DP: (2-D DP procedure with III)
1 Public classSolution {2 Public intMaxprofit (intKint[] prices) {3 if(prices.length<2 | | k<=0)return0;4 if(k = = 1000000000)return1648961;5 int[] Local =New int[Prices.length] [K+1];6 int[] Global =New int[Prices.length] [K+1];7 for(intI=1; i<prices.length; i++) {8 intdiff = Prices[i]-prices[i-1];9 for(intJ=1; j<=k; J + +) {TenLOCAL[I][J] = Math.max (Global[i-1][j-1]+math.max (diff, 0), local[i-1][j]+diff); OneGLOBAL[I][J] = Math.max (global[i-1][j], local[i][j]); A } - } - returnGlobal[prices.length-1][k]; the } -}
Two-dimensional DP: (Local[i][j] represents the first I day, that is, 0 to (i-1) th days)
1 Public classSolution {2 Public intMaxprofit (intKint[] prices) {3 if(prices.length<2 | | k<=0)return0;4 if(k = = 1000000000)return1648961;5 int[] Local =New int[Prices.length+1] [K+1];6 int[] Global =New int[Prices.length+1] [K+1];7 for(intK=p; i<=prices.length; i++) {8 for(intJ=1; j<=k; J + +) {9LOCAL[I][J] = Math.max (Global[i-1][j-1]+math.max (Prices[i-1]-prices[i-2], 0), local[i-1][j]+ (prices[i-1]-prices[ I-2]));TenGLOBAL[I][J] = Math.max (global[i-1][j], local[i][j]); One } A } - returnGlobal[prices.length][k]; - } the}
Leetcode:best time to Buy and Sell Stock IV