You are given an array prices where prices[i] is the price of a given stock on the ith day.
Find the maximum profit you can achieve. You may complete at most two transactions.
Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
classSolution { public: intmaxProfit(vector<int>& p){ vector<int> dp(p.size()); int mi = p[0], ma = p.back(), n = p.size(), res = 0; for(int i = 1; i < n; i++) { dp[i] = max(p[i] - mi, dp[i-1]); mi = min(mi, p[i]); } res = dp.back(); for(int i = n - 2; i > 0; i--) { res = max({res, dp[i-1] + ma - p[i], dp[i]}); ma = max(ma, p[i]); } return res; } };