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.
The subject only needs to be traversed once, maintaining two pointers, one pointing to the lowest price before I, one pointing to the lowest price, and the highest price before I, if prices[i] is higher than high, then the update is Prices[i],
If Prices[i]<low, calculate the high-low to see if you want to update the maximum profit, and then both high and low point to I.
Code:
1 intMaxprofit (vector<int>&prices)2 {3 if(prices.size () = =0|| Prices.size () = =1)4 return 0;5 intlow=prices[0],high=prices[0],profit=0;6 for(intI=1; I<prices.size (); i++)7 {8 if(prices[i]>High )9High=Prices[i];Ten Else if(prices[i]<Low ) One { A if(profitLow ) -profit=high-Low ; -low=Prices[i]; theHigh=Prices[i]; - } - } - intpre=high-Low ; + returnPre>profit?Pre:profit; -}
121. Best time to Buy and Sell Stock