https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/
数组的最大2子段和,允许在一天内买入又卖出,相当于不交易。因为题目规定的是最多交易两次,而不是必须交易两次。
class Solution {
public:int maxProfit(vector<int>& prices) {int n = prices.size();if(n<2) return 0;vector<int> f(n,0);vector<int> g(n,0);int i;int mini = prices[0];for(i=1;i<n;i++){mini=min(prices[i], mini);f[i]=max(prices[i]-mini, f[i-1]);}int maxi = prices[n-1];for(i=n-2;i>-1;i--){maxi=max(prices[i], maxi);g[i]=max(maxi-prices[i], g[i+1]);}int result = 0;for(i=0;i<n;i++){result = max(result, f[i]+g[i]);}return result;}
};