Leetcode notes: Best Time to Buy and Stock III

Source: Internet
Author: User

Leetcode notes: Best Time to Buy and Stock III

I. Description

Say you have 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 may complete at most two transactions.

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

Ii. Question Analysis

Compared with the previous two questions, this question limits the number of stock transactions and can only be traded twice at most.

You can use dynamic planning to complete the process. The first step is to scan and calculate the sequence.[0, …, i]Maximum profit inprofit, Using an arrayf1Save, the time complexity of this step isO(n).

Step 2: reverse scanning to calculate subsequences[i, …, n - 1]Maximum profit inprofit, Using an arrayf2Save, the time complexity of this step is alsoO(n).

The last step,f1 + f2To find the maximum value.

Iii. Sample Code

#include 
  
   #include 
   
    using namespace std;class Solution {public:    int maxProfit(vector
    
      &prices)     {        int size = prices.size();        if (size <= 1) return 0;        vector
     
       f1(size);        vector
      
        f2(size); int minV = prices[0]; for (int i = 1; i < size; ++i) { minV = std::min(minV, prices[i]); f1[i] = std::max(f1[i - 1], prices[i] - minV); } int maxV = prices[size - 1]; f2[size - 1] = 0; for (int i = size-2; i >= 0; --i) { maxV = std::max(maxV, prices[i]); f2[i] = std::max(f2[i + 1], maxV - prices[i]); } int sum = 0; for (int i = 0; i < size; ++i) sum = std::max(sum, f1[i] + f2[i]); return sum; }};
      
     
    
   
  

Iv. Summary

Compared with the first two questions, this question is more difficult, and there are several questions related to this question. Subsequent Updates...

 

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.