地址: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 &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;
}
};