地址: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).
2. 逆序遍历记录当前开始到最后一次可以获取的最大利润,记录并更新从尾开始的最大值。
如果在某个点有重复,即之前获得的最大值的终点和之后获得的最大值的起点是同一点,其实就是一次交易。比如 3 1 2 7 10, 顺序遍历会记录3->7,逆序会记录7->10,如果在这个点有最大值,其实就是一次交易。如果不发生在实际的同一点(注意当前交易所得并不一定是最大,可能会被之前更大的值更新),那就是两次交易和。
参考代码:80ms
class Solution {
public:
int maxProfit(vector<int> &prices) {
if(prices.size()<=1)
return 0;
int buy_low = INT_MAX, sell_high = INT_MIN, profit = 0, ans = 0;
vector<int>first_profit(prices.size(), 0);
for(int i = 0; i<prices.size(); ++i)
{
if(prices[i]<buy_low)
buy_low = prices[i];
else
profit = max(profit, prices[i]-buy_low);
first_profit[i] = profit;
}
profit = 0;
for(int i = prices.size()-1; 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, 60msclass 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 ;}};