best time to Buy and Sell Stock III
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).
Dpback[i] for the maximum benefit from the first day to the day I dpafter[j] for the maximum benefit from the J Day to the last day how to maximize revenue consider the method of using best time to buy and Sell Stock I note that you can buy up to two times or only once
1 classSolution {2 Public:3 intMaxprofit (vector<int> &prices) {4 5 intn=prices.size ();6 if(n==0)return 0;7 8vector<int>dpback (n), Dpafter (n);9 Ten intmaxprofit=0; Onedpback[0]=0; A intleft=prices[0]; - - for(intI=1; i<n;i++) the { - if(prices[i]>Left ) - { - if(Maxprofit<prices[i]-left) maxprofit=prices[i]-Left ; + } - Else + { Aleft=Prices[i]; at } - -dpback[i]=Maxprofit; - } - -maxprofit=0; indpafter[n-1]=0; - intright=prices[n-1]; to + for(intj=n-2; j>=0; j--) - { the if(prices[j]<Right ) * { $ if(Maxprofit<right-prices[j]) maxprofit=right-Prices[j];Panax Notoginseng } - Else the { +right=Prices[j]; A } the +dpafter[j]=Maxprofit; - } $ $ intresult=0; - for(intI=0; i<n-1; i++) - { the if(dpback[i]+dpafter[i+1]>result) result=dpback[i]+dpafter[i+1]; - Wuyi if(result<dpback[i+1]) result=dpback[i+1]; the } - Wu returnresult; - } About};
"Leetcode" best time to Buy and Sell Stock III