/** 188. best time to Buy and Sell Stock IV * 2016-6-6 by Mingyang * This topic my approach is to set up a number of transaction for the two-dimensional dp,t[i][j]i, J is the days * Also is to complete the maximum value of the I transaction within J days * T[i][j]=max 1. T[I][J-1]------> J Day does not trade at all * 2. (Prices[j]-prices[m]) +t[i-1][m]------all the maximum * for m=0,... j-1---that is, in M days to complete i-1 transactions, the last time by M buy, J Sell*/ Public intMaxprofit (intKint[] prices) { intlen=prices.length; if(prices==NULL|| Len==0) return0; int[] t=New int[K+1][prices.length]; for(inti=0;i<=k;i++) {t[i][0]=0; } for(intj=0;j<prices.length;j++) {t[0][j]=0; } for(inti=1;i<=k;i++){ for(intj=1;j<prices.length;j++){ intMaxval=0; for(intm=0;m<j;m++) {Maxval=math.max (maxval,prices[j]-prices[m]+t[i-1][m]); } T[i][j]=math.max (t[i][j-1],maxval); } } returnT[k][prices.length-1]; }
188. Best time to Buy and Sell Stock IV