Known stock price sequence, calculating when to buy and sell the most benefit

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.