"Leetcode" best time to Buy and Sell Stock III

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).

Dpback[i] for the maximum benefit from the first day to the day I dpafter[j] for the maximum benefit from the J Day to the last day how to maximize revenue consider the method of using best time to buy and Sell Stock I note that you can buy up to two times or only once
1 classSolution {2  Public:3     intMaxprofit (vector<int> &prices) {4        5         intn=prices.size ();6         if(n==0)return 0;7  8vector<int>dpback (n), Dpafter (n);9  Ten         intmaxprofit=0; Onedpback[0]=0; A         intleft=prices[0]; -         -          for(intI=1; i<n;i++) the         { -             if(prices[i]>Left ) -             { -                if(Maxprofit<prices[i]-left) maxprofit=prices[i]-Left ; +             } -             Else +             { Aleft=Prices[i]; at             } -             -dpback[i]=Maxprofit; -         } -         -maxprofit=0; indpafter[n-1]=0; -         intright=prices[n-1]; to         +          for(intj=n-2; j>=0; j--) -         { the             if(prices[j]<Right ) *             { $                 if(Maxprofit<right-prices[j]) maxprofit=right-Prices[j];Panax Notoginseng             } -             Else the             { +right=Prices[j]; A             } the   +dpafter[j]=Maxprofit; -         } $         $         intresult=0; -          for(intI=0; i<n-1; i++) -         { the             if(dpback[i]+dpafter[i+1]>result) result=dpback[i]+dpafter[i+1]; -            Wuyi             if(result<dpback[i+1]) result=dpback[i+1]; the         } -         Wu         returnresult; -     } About};

"Leetcode" best time to Buy and Sell Stock III

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.