问题:
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).
建立两个一维table,left和right。其中left[i]保存的是在第i天之前做一次交易的最大profit;right[i]保存的是在第i天之后做一次交易的最大profit。那么我们最后只需要找到max(left[i] + right[i])即可。那么这两个table怎么建立呢?以left为例(right类似),从做向右推,到第i个位置时候,我们面临两个选择:1)这次交易是在第i天卖出;2)这次交易不是在第i天卖出,也就是在之前的某一天卖出。所以我们有了:left[i] = max(price[i] - min_val, left[i-1]),其中min_val是i天之前的所有价格中的最小值。因此只需遍历一次,我们就可以建立left table,也只需一次(从后向前),我们就可以建立right table。
代码:(O(n))
class Solution {
public:
int maxProfit(vector<int> &prices) {
int len = prices.size();
if (len <= 1) return 0;
int left[len];
left[0] = 0;
int min_val = prices[0];
for (int i = 1; i < len; i ++) {
left[i] = std::max(left[i-1], prices[i] - min_val);
min_val = std::min(prices[i], min_val);
}
int right[len];
right[len - 1] = 0;
int max_val = prices[len - 1];
for (int i = len - 2; i >= 0; i --) {
right[i] = std::max(right[i + 1], max_val - prices[i]);
max_val = std::max(max_val, prices[i]);
}
int result = -1;
for (int i = 0; i < len; i ++) {
result = max(result, left[i] + right[i]);
}
return result;
}
};