class Solution {
public:
int maxProfit(vector<int>& prices) {
int size = prices.size();
if (size < 2) {
return 0;
}
//對某一天來說, 第一次交易 (該天價格 - 最小價格)
vector<int> first(prices.size(), 0);
int minV = prices[0];
for (int i = 1; i < size; i++) {
first[i] = max(first[i - 1], (prices[i] - minV));
minV = min(minV, prices[i]);
}
//對某一天來說, 第二次交易 (最大價格 - 該天價格)
int maxV = prices[size - 1];
int res = 0;
for (int i = size - 2; i >= 0; i--) {
maxV = max(maxV, prices[i]);
res = max(res, (maxV - prices[i] + first[i]));
}
return res;
}
};