"Leetcode" best time to Buy and Sell Stock III (2 solutions)

Source: Internet
Author: User

best time to Buy and Sell Stock III

Say you has an array for which the i-th element is the price of a given-stock on day I.

Design an algorithm to find the maximum profit. You are in most of the transactions.

Note:
Engage in multiple transactions on the same time (ie, you must sell the stock before you buy again).

Solution one: Based on best time to Buy and Sell Stock

The code is long, but the idea is still relatively clear, listen to my explanation:

Core idea:

The first step: the Best Buy and Sell stock in accordance with the optimal trading. The value is maxgap and the buy and sell points are recorded as Minind and Maxind.

The second step: there are two kinds of situations

CASE1: On the basis of optimal trading, add another effective trading.

CASE2: Split the best deal, that is minind in the first sale, maxind in the second sale.

Look at the simple, next we tangled border situation:

CASE1: There is no intersection between the new effective trading and the optimal trading. In other words, before minind strict or maxind strict.

CASE2: The first buy and sell points are likely to be minind, the second sale of the selling point and selling points are likely to be maxind.

Realize:

Case1 is easy, is to run two times the best trading, merit to join. If there is no valid trade, it is recorded as 0.

The best Buy and sell before Minind is recorded as PARTGAP2 after Partgap1,maxind.

Case1result = Maxgap + Max (PARTGAP1, PARTGAP2);

Case2 more trouble, let us explain in detail:

Simple analysis reveals:

The value of two transactions is <minleft, Prices[j]>,<prices[k], maxright>

Where Minleft is the minimum value before Minind, including the Minind. Minleft is the value of the first buy point, Prices[j] is the value of the first selling points.

Maxright is the maximum value after maxind, including the Maxind. PRICES[K] is the value of the second buy point, Maxright is the value of the second sale.

Therefore, the following conditions must be met:

(1) Minleft location <=minind, J>=minind

(2) K<=maxind, maxright location >=maxind

(3) J<=k meet the conditions of the note

Case2result = Prices[j]-minleft+maxright-prices[k]

Because both Minleft and maxright are deterministic, maximizing case2result requires only the maximum value of prices[j]-prices[k].

This problem is attributed to the "worst deal", that is, the inverse problem of the optimal buying and selling problem, high buy, low sell.

In order to save the calculation, in the implementation process, Minleft and Maxright are included in the CASE1 calculation process.

It is important to note that CASE1 does not contain boundaries, so minleft and maxright should also be weighed against minind and maxind values.

classSolution { Public:    intMaxprofit (vector<int> &prices) {        if(Prices.empty ())return 0; //At least 1 element        intMAXV = prices[0]; intMaxind =0; intMINV = prices[0]; intMinind =0; intCurgap =0; intMaxgap =0;  for(vector<int>::size_type st =1; St < Prices.size (); St + +)        {            if(Prices[st] >MAXV) {//MAXV is free to updateMAXV =Prices[st]; Curgap= maxv-MINV; if(Curgap >maxgap) {Maxgap=Curgap; Maxind=St; //Minind is the landmark position, changing all the time, thus cannot be determined                }            }            Else if(Prices[st] <MINV) {//If MINV changes, all should restartMINV =Prices[st]; MAXV=Prices[st]; Curgap=0; }        }        //Get the Minind         for(vector<int>::size_type st =0; St < Prices.size (); St + +)        {            if(Prices[maxind]-prices[st] = =maxgap) {Minind=St;  Break; }        }        //arrive here, Maxgap, Maxind, Minind is needed, thus avoid changing value//Case 1:the Minind~max is covered and add the 0~minind (PARTGAP1) or max~size-1 (PARTGAP2)MAXV = prices[0]; MINV= prices[0]; Curgap=0; intPartGap1 =0; //Minleft can be prices[minind]        intMinleft =Prices[minind];  for(vector<int>::size_type st =1; St < Minind; St + +) {Minleft=min (Minleft, prices[st]); if(Prices[st] >MAXV) {//MAXV is free to updateMAXV =Prices[st]; Curgap= maxv-MINV; if(Curgap >partGap1) PartGap1=Curgap; }            Else if(Prices[st] <MINV) {//If MINV changes, all should restartMINV =Prices[st]; MAXV=Prices[st]; Curgap=0; }} MAXV= prices[maxind+1]; MINV= prices[maxind+1]; Curgap=0; intPARTGAP2 =0; //if Maxind is greater than prices.size () -3, then PARTGAP2 remains 0.        intMaxright = Prices[maxind];//maxright initialized to Prices[maxind]         for(vector<int>::size_type st = maxind+1; St < Prices.size (); St + +) {Maxright=Max (Maxright, prices[st]); if(Prices[st] >MAXV) {//MAXV is free to updateMAXV =Prices[st]; Curgap= maxv-MINV; if(Curgap >partGap2) PartGap2=Curgap; }            Else if(Prices[st] <MINV) {//If MINV changes, all should restartMINV =Prices[st]; MAXV=Prices[st]; Curgap=0; }        }        //arrive, PARTGAP2, maxright is needed//Caseresult May is either maxgap itself or adding one part        intCase1result = maxgap+Max (PARTGAP1, PARTGAP2); //Case 2:i (Index of Minleft<minind) ~minind~j add k~maxind~l (Index of maxright>k)//Case2result = Prices[j]-minleft+maxright-prices[k], that's Max (Prices[j]-prices[k]) && j<=kMAXV = Prices[minind];//JMINV = Prices[minind];//kCurgap =0; Maxgap=0;//Now Maxgap can changed        intTmpind =Minind;  for(vector<int>::size_type st = Minind; St <= Maxind; St + +)        {            if(Prices[st] <MINV) {MINV=Prices[st]; Curgap= maxv-MINV; if(Curgap >maxgap) {Maxgap=Curgap; Tmpind=St; //Maxind is the landmark position, changing all the time, thus cannot be determined                }            }            Else if(Prices[st] >MAXV) {MAXV=Prices[st]; MINV=Prices[st]; Curgap=0; }        }        intCase2result = maxgap-minleft+Maxright; returnMax (Case1result, Case2result); }};

Solution Two: Dynamic programming

Use two arrays, Maxvec and Minvec.

Maxvec[i] represents the optimal trading value from 0 to I (Low buy high sell, positive). You need to traverse from left to right at once.

Minvec[i] Represents the worst trade-off value from size-1 to I (shoplifting low sell, negative). You need to traverse from right to left at once.

Iterate through the array one at a time, subtracting the corresponding element: the maximum value of maxvec[i]-minvec[i] is the solution.

A little analysis of the discovery, in fact, Minvec is not required, in the right to the left when the current value Mingap is minvec[i],

Calculate MAXVEC[I]-MINGAP directly to update the results. This will also eliminate the last traversal on the array.

classSolution { Public:    intMaxprofit (vector<int> &prices) {        if(Prices.empty ())return 0; intSize =prices.size (); intMinleft = prices[0]; intMaxgap =0; //Maxvec[i] means the maxgap from start to I (--)vector<int> Maxvec (Size,0); intMaxright = prices[size-1]; intMingap =0; //Minvec[i] means the mingap from end to I (<--)//vector<int> Minvec (size, 0);                intresult =0;  for(inti =0; i < size; i + +)        {            if(Prices[i]-minleft >maxgap)//Current is very bigMaxgap = prices[i]-Minleft; Else if(Prices[i] <minleft)//Current is very smallMinleft =Prices[i]; Maxvec[i]=Maxgap; }         for(inti = size-1; I >=0; I--)        {            if(Prices[i]-maxright <mingap)//Current is very smallMingap = prices[i]-Maxright; Else if(Prices[i] >maxright)//Current is very bigMaxright =Prices[i]; //Minvec[i] = mingap;                        if(maxvec[i]-mingap>result) Result= maxvec[i]-Mingap; }        returnresult; }};

"Leetcode" best time to Buy and Sell Stock III (2 solutions)

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.