题目:
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次,假设两次交易分别发生在下标i的左右两边。
f[i]表示截止到下标i位置,左边得到的最大利润;g[i]表示截止到下标i位置,右边得到的最大利润。
求f[i]+g[i]的最大值。
class Solution {
public:
int maxProfit(vector<int> &prices) {
int length = prices.size();
if(length < 2)
return 0;
vector<int> left_max(length,0);
vector<int> right_max(length,0);
//先买入
int cur_min = prices[0];
for(int i = 1; i < length; i++) {
left_max[i] = max(prices[i] - cur_min, left_max[i-1]);
cur_min = min(cur_min, prices[i]);
}
int cur_max = prices[length-1];
//需要逆序,从右向左,先抛售
for(int i = length-2; i > 0; i--) {
right_max[i] = max(cur_max - prices[i], right_max[i+1]);
cur_max = max(cur_max, prices[i]);
}
int sum = 0;
for(int i = 1; i < length; i++) {
sum = max(sum, left_max[i] + right_max[i]);
}
return sum;
}
private:
int max(const int &a, const int &b) {
return a > b ? a : b;
}
int min(const int &a, const int &b) {
return a < b ? a : b;
}
};