Question: A stock price sequence, known at each point in time, to ask when to buy and sell the most profit? Time complexity O (n).
Suppose the stock price is placed in an array in chronological order, assuming that the stock price rises and falls, that is, the stock price sequence is not diminishing. Buy and sell points need to be recorded (in lieu of array subscripts).
(1) The maximum profit value is initialized to Int_min. The buy price and buy point are initialized to the first element of the array.
(2) Iterate through the array from the second element, and take profit if the current stock price is higher than the buy price. If the maximum value is greater than the current profit, the profit maximum and the sell point are modified.
(3) If the current stock price is less than or equal to the buy price, the buy price and buy point are placed at the current point.
The code is as follows:
intBestbenifit (intArr[],intNint& Buy,int&sell) {Assert (arr! = NULL && n >1); Buy=0; Sell=0; intMax =int_min; intBuy_p = arr[0]; for(inti =1; I < n; i++) { if(Arr[i] >buy_p) { if(Max < arr[i]-buy_p) {Max= Arr[i]-buy_p; Sell=i; } } Else{buy_p=Arr[i]; Buy=i; } } returnMax;}
If you consider a decrease in the stock price, for any number of loops, calculate the value of the current stock and bid price, and compare it to Max.
Known stock price sequence, calculation of when to buy and sell the most benefit