点击打开链接
class Solution {
public:
int maxProfit(vector<int>& prices) {
int n = prices.size(), result = 0;
if(n<2) return 0;
vector<int> f(n, 0), g(n,0);
for(int i=0, low=prices[0]; i<n; i++){
low = min(low, prices[i]);
f[i] = max(f[i-1], prices[i]-low);
}
for(int i= n-2,high = prices[n-1]; i>=0; i--){
high = max(high, prices[i]);
g[i] = max(g[i+1], high-prices[i]);
}
for(int i=0; i<n;i++){
result = max(result, f[i]+g[i]);
}
return result;
}
};