123. 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).
Dynamic planning, Preprofit save before I trade gains. Postprofit the proceeds from the transaction after saving I.
Max{preprofit[i]+postprofit[i]} is the greatest possible benefit.
classSolution { Public: intMaxprofit (vector<int>&prices) { intSize=prices.size (); if(size<2) return 0; intcurmin=prices[0],curmax=prices[size-1]; Vector<int> preprofit (Size,0); Vector<int> postprofit (Size,0); for(intI=1; i<size;i++) {curmin=min (curmin,prices[i]); Preprofit[i]=max (preprofit[i-1],prices[i]-curmin); } for(intj = size-1;j>0; --j) {Curmax=Max (curmax,prices[j]); POSTPROFIT[J]=max (postprofit[j-1],curmax-Prices[j]); } intretprofit=0; for(intm=0; m<size;m++){ if(retprofit< (preprofit[m]+Postprofit[m])) Retprofit=preprofit[m]+Postprofit[m]; } returnRetprofit; }};
[Leetcode]123. best time to Buy and Sell Stock III