Best time to buy and keep stock III <leetcode>

Source: Internet
Author: User

Say you have an array for whichITh element is the price of a given stock on dayI.

Design an algorithm to find the maximum profit. You may complete at mostTwoTransactions.

Note:
You may not engage in multiple transactions at the same time (ie, you must encrypt the stock before you buy again ).

 

 

Idea: This question is originally divided into two parts, respectively, with dynamic planning. Later, due to the first question, I saw a relatively simple dynamic planning, so here we use it directly. (although the code is written differently, the idea is different, but we use dynamic planning.) Let's look at the concise dynamic planning code:

 

 1 class Solution { 2 public: 3     int maxProfit(vector<int> &prices) { 4     int minl=INT_MAX; 5     int maxr=INT_MIN; 6      7     int size=prices.size(); 8     if(size==0)  return 0; 9     vector<int> f1(size);10     vector<int> f2(size);11     12     minl=prices[0];13     14     for(int i=1;i<size;i++)15     {16         minl=min(minl,prices[i]);17         f1[i]=max(f1[i-1],prices[i]-minl);18     }19     20     maxr=prices[size-1];21     22     for(int i=size-2;i>=0;i--)23     {24        maxr=max(maxr,prices[i]); 25        f2[i]=max(f2[i+1],maxr-prices[i]);26     }27     28     int sum = 0;29         for (int i = 0; i < size; i++)30             sum = std::max(sum, f1[i] + f2[i]);31 32         return sum;33     }34 };

 

Best time to buy and keep stock III <leetcode>

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.