Topic:
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. You are in most of the transactions.
Note:
Engage in multiple transactions on the same time (ie, you must sell the stock before you buy again).
The following:
According to the requirements of the title, up to two times to buy and sell stocks, and the hands can not have 2 stocks, is not two consecutive buy operations.
Therefore, two trades must be distributed within 2 intervals, that is, the action is: buy sell, buy sell.
Further, we can divide into 2 intervals [0,i] and [I,len-1],i can take 0~len-1.
Then the maximum profit for the two trades is: the maximum profit in two intervals and the maximum profits.
The maximum benefit of a division is: profit[i] = Maxprofit (interval [0,i]) + maxprofit (interval [i,len-1]);
The final maximum profit is: Maxprofit (profit[0], profit[1], profit[2], ..., profit[len-1]).
The code is as follows:
1 Public intMaxprofit (int[] prices) { 2 if(Prices = =NULL|| Prices.length <= 1){ 3 return0; 4 } 5 intLen =prices.length; 6 intMaxprofit = 0; 7 intMin = prices[0]; 8 intArraya[] =New int[Len]; 9 Ten for(inti=1;i<prices.length;i++){ Onemin=math.min (Min,prices[i]); AArraya[i]=math.max (arraya[i-1],prices[i]-min); - } - the intmax = Prices[len-1]; - intArrayb[] =New int[Len]; - for(inti = len-2; I >= 0; i--){ -Max =Math.max (Prices[i],max); +Arrayb[i] = Math.max (max-prices[i],arrayb[i+1]); - } + A for(inti = 0; i < Len; i++){ atMaxprofit = Math.max (Maxprofit,arraya[i] +arrayb[i]); - } - - returnMaxprofit; -}
Operation Result:
int[] prices = {3,2,7,4,5,10}
Arraya:[0, 0, 5, 5, 5, 8]
Arrayb:[8, 8, 6, 6, 5, 0]
Maxprofit:11
Reference
Http://www.cnblogs.com/springfor/p/3877068.html
http://blog.csdn.net/u013027996/article/details/19414967
*best time to Buy and Sell Stock III