class Solution { public: int maxProfit(vector<int>& prices) { if(prices.size() < 2)return 0; int len = prices.size(), minPrice = prices[0], res = 0; vector<int> dp(len, 0); for(int i = 0; i < len; ++i) { minPrice = min(minPrice, prices[i]); dp[i] = max(dp[i - 1], prices[i] - minPrice); } int maxPrice = INT_MIN, currMaxProfit = 0; for(int i = len - 1; i >= 0; --i) { maxPrice = max(maxPrice, prices[i]); currMaxProfit = max(currMaxProfit, maxPrice - prices[i]); res = max(res, dp[i] + currMaxProfit); } return res; } };