best-time-to-buy-and-sell-stock-iii

Title Description

 

Say you have an array for which the i th element is the price of a given stock on day i.

AN algorithm to the Find at The Design maximum Profit. By You May Complete AT MOST  TWO  Transactions. (Maximum of two trading)

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

Idea: Suppose the number in your hand and now the money is zero. buy1, it is recorded from day 1 to day i lowest price you can buy (buy, so debts, so the record is negative, so use max), sell1, is recorded on day 1 to i days of the day, you sell, how much money can earn the most. buy2 and sell2 a prerequisite is that you have the i-th day before, whether or not the first transaction, if carried out, then the first transaction with a profit in the calculation down, so you are the first deal with profit, calculated, so then, if you conducted a transaction, then that is the maximum value of two times the transaction. If you are in the i days ago, no transactions, and so buy1 buy2 actually the same, sell1 and sell2 is the same, no change.
class Solution {
 public :
     int MAXPROFIT (Vector < int > & Prices) {
         IF (prices.size () <= . 1 )
             return  0 ;
         int buy1 = INT_MIN;
         int sell1 = 0 ; // first time when the selling profit 
        int = buy2 INT_MIN;
         int sell2 = 0 ; // profit selling at the second, i.e. total profit 
        for ( int I = 0 ; I <prices.size (); ++ I) 
        { 
            buy1=max(buy1,-prices[i]);
            sell1=max(sell1,buy1+prices[i]);
            buy2=max(buy2,sell1-prices[i]);
            sell2=max(sell2,buy2+prices[i]);
        }
        return sell2;
    }
};

 

Guess you like

Origin www.cnblogs.com/lijingblog/p/11025429.html