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

地址:http://oj.leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/

Say you have an array for which the ith 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 sell the stock before you buy again).

思路:1. 顺序遍历记录当前为止一次可以获取的最大利润,记录并更新从头开始的最小值。

           2. 逆序遍历记录当前开始到最后一次可以获取的最大利润,记录并更新从尾开始的最大值。

            如果在某个点有重复,即之前获得的最大值的终点和之后获得的最大值的起点是同一点,其实就是一次交易。比如 3 1 2 7 10, 顺序遍历会记录3->7,逆序会记录7->10,如果在这个点有最大值,其实就是一次交易。如果不发生在实际的同一点(注意当前交易所得并不一定是最大,可能会被之前更大的值更新),那就是两次交易和。

参考代码:80ms

class Solution {
public:
    int maxProfit(vector &prices) {
        if(prices.size()<=1)
            return 0;
        int buy_low = INT_MAX, sell_high = INT_MIN, profit = 0, ans = 0;
        vectorfirst_profit(prices.size(), 0);
        for(int i = 0; i=0; --i)
        {
            if(prices[i]>sell_high)
                sell_high = prices[i];
            else
                profit = max(profit, sell_high - prices[i]);
            ans = max(ans, first_profit[i] + profit);
        }
        return ans;
    }
};


 
  
//SECOND TRIAL, 60ms
class Solution {
public :
     int maxProfit ( vector < int > & prices ) {
         if ( prices . size () <= 1 )
             return 0 ;
         vector < int > v1 ( prices . size (), 0 ), v2 ( prices . size (), 0 );
         int low = prices [ 0 ], high = prices [ prices . size () - 1 ];
         for ( int i = 1 ; i < prices . size (); ++ i )
         {
             low = min ( low , prices [ i ]);
             v1 [ i ] = max ( v1 [ i - 1 ], prices [ i ] - low );
         }
            
         for ( int j = prices . size () - 2 ; j >= 0 ; -- j )
         {
             high = max ( high , prices [ j ]);
             v2 [ j ] = max ( v2 [ j + 1 ], high - prices [ j ]);
         }
         int ans = 0 ;
         for ( int i = 0 ; i < prices . size (); ++ i )
             ans = max ( ans , v1 [ i ] + v2 [ i ]);
         return ans ;
     }
};


你可能感兴趣的:(Leetcode)