"Simple Algorithm" 34. The best time to buy and sell stocks

Source: Internet
Author: User

Topic:

given an array, the first element of it is the price of the first day of a given stock. If you are only allowed to complete a single trade (i.e. buy and sell a stock), design an algorithm to calculate the maximum profit you can get. Note that you cannot sell stocks before buying stocks. Example1: Enter: [7,1,5,3,6,4] Output:5Explanation: in section2Day (stock price =1) when buying, in the first5Day (stock price =6) When selling, the maximum Profit =6-1=5. Note that profit cannot be7-1=6because the sell price needs to be greater than the buy price. Example2: Enter: [7,6,4,3,1] Output:0explanation: In this case, no transaction is completed, so the maximum profit is0。

Problem Solving Ideas:

Use the day after minus the day before to get the next profit, and then convert the topic to the maximum number of sub-sequences and problems.

classSolution { Public:    intMaxprofit (vector<int>&prices) {Vector<int>profit; intMaxres =0; intsum =0;  for(inti =1; I < prices.size (); ++i) {profit.push_back (Prices[i]-prices[i-1]); }                 for(inti =0; i < profit.size (); + +i) {Sum+=Profit[i]; if(Sum >0) {Maxres=Max (sum,maxres); }Else{sum=0; }        }                returnMaxres; }};

Another solution, the price of the day minus the minimum value of the previous stock today:

classSolution { Public:    intMaxprofit (vector<int>&prices) {Vector<int> Minleft (prices.size (),0); intres =0; if(Prices.size () <=0){            return 0; }                intMinval =Int_max;  for(inti =0; i < prices.size (); ++i) {Minval=min (minval,prices[i]); Minleft[i]=Minval; }                 for(inti =1; i < prices.size (); ++i) {Res= Max (prices[i]-minleft[i-1],res); }                returnRes; }};

"Simple Algorithm" 34. The best time to buy and sell stocks

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.