Best time to buy and buy stock III

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 most two transactions.

Note:

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

Idea: Use the idea of Dynamic Planning: traverse the array from front to back and from back to back, respectively, find the maximum profits in the range a [0]-A [I] And a [I]-A [n. Then, traverse the array again to find out the first part of the profit and the next part of the profit plus the maximum profit value. The time complexity is O (n ).

 1 class Solution { 2 public: 3     int maxProfit( vector<int> &prices ) { 4         int size = prices.size(); 5         if( size <= 1 ) { return 0; } 6         vector<int> invMaxProfit( size, 0 ); 7         int curMax = prices[size-1]; 8         for( int i = size-2; i >= 0; --i ) { 9             if( curMax <= prices[i] ) {10                 curMax = prices[i];11             } else {12                 invMaxProfit[i] = curMax - prices[i];13             }14         }15         int curMin = prices[0], profit = 0, totalProfit = invMaxProfit[0];16         for( int i = 0; i < size-1; ++i ) {17             if( curMin > prices[i] ) { curMin = prices[i]; }18             if( profit < prices[i] - curMin ) { profit = prices[i] - curMin; }19             if( totalProfit < profit + invMaxProfit[i+1] ) { totalProfit = profit + invMaxProfit[i+1]; }20         }21         return totalProfit;22     }23 };

 

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.