Up to two stock trades-best time to Buy and Sell stock III

Source: Internet
Author: User

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. Transactions. (Stock trading , up to two times)

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

Class Solution {public:    int maxprofit (vector<int> &prices) {        if (prices.size () ==0) return 0;        int n=prices.size ();        Vector<int> left (n);        Vector<int> right (n);        int min=prices[0];        int max=prices[n-1];        int res=0;        for (int i=1;i<n;i++)        {            min=min<prices[i]?min:prices[i];            Left[i]=left[i-1]> (prices[i]-min) left[i-1]:(prices[i]-min);        }        for (int j=n-2;j>=0;j--)        {            max=max>prices[j]?max:prices[j];            Right[j]=right[j+1]> (Max-prices[j]) right[j+1]:(max-prices[j]);        }        for (int i=0;i<n;i++)        {            res=res> (Left[i]+right[i]) Res: (Left[i]+right[i]);        }        return res;    }};

  

Up to two stock trades-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.