Say you has an array for which the i-th element is the price of a given-stock on day I.
If you were-permitted-to-complete at most one transaction (ie, buy one and sell one share of the stock), design an AL Gorithm to find the maximum profit.
Ideas: In disguise to find the largest sub-array, is an example of the introduction of the algorithm, the book by the division of the law.
If prices=[1,4,2,8,1], the profit per two-digit subtraction, that is, the first day to buy, the next day to sell.
PROFIT=[0,3,-2,6,-7], you can see the first day to buy, the last day to sell the profit for the (-2) +6+ (-7) =0
Code:
classSolution { Public: intMaxprofit (vector<int> &prices) { intlen=prices.size (); intres=0; inttemp=0; if(len==0)returnRes; Vector<int> Profit (len,0); Vector<int> dp (LEN,0); for(intI=0; i<len;++i) { if(i==0) {profit[i]=0;Continue;} Profit[i]=prices[i]-prices[i-1]; } dp[0]=profit[0]; for(intI=1; i<len;++i) {Dp[i]=max (dp[i-1]+Profit[i],profit[i]); if(dp[i]>Res) Res=Dp[i]; } returnRes; }};
best time to Buy and Sell Stock (Dynamic planning)