题目描述:
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).
使用两个辅助数组,f1和f2,f1[i]表示在第i支股票之前完成一次交易能够获得的最大利润;
f2[i]表示在第i支股票之后完成一次交易能够获得的最大利润;那么完成两次交易能够获得
的最大利润为:max(f1[i]+f2[i])
AC代码如下:
class Solution {
public:
int maxProfit(vector<int>& prices) {
int size = prices.size();
if (size == 0) return 0;
vector<int> f1(size);
vector<int> f2(size);
int minV = prices[0];
for (int i = 1; i < size; ++i){
minV = min(minV, prices[i]); //minV表示第i支股票前(包括第i支股票)的最低的股票的价格
f1[i] = max(f1[i - 1], prices[i] - minV); //f1[i]表示在第i支股票之前完成一次交易能够获得的最大利润
}
int maxV = prices[size - 1];
f2[size - 1] = 0;
for (int i = size - 2; i >= 0; --i){
maxV = max(maxV, prices[i]); //maxV表示第i支股票后(包括第i支股票)的最高的股票的价格
f2[i] = max(f2[i + 1], maxV - prices[i]); //f2[i]表示在第i支股票之后完成一次交易能够获得的最大利润
}
int sum = 0;
for (int i = 0; i < size; ++i)
sum = max(sum, f1[i] + f2[i]); //完成两次交易能够获得的最大利润为:max(f1[i] + f2[i])
return sum;
}
};