# LeetCode Best Time to Buy and Sell Stock III

LeetCode Best Time to Buy and Sell Stock III

Say you have an array for which the ith element is the price of a given stock on day i.

Design an algorithm to find the maximum profit. You may complete at most two transactions.

Note:
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

 prices 3 2 6 5 0 3 min_so_far INT_MAX 3 2 2 2 0 max_so_far 6 6 5 3 3 INT_MIN profit1 0 0 4 4 4 4 profit2 4 4 3 3 3 0 total 4 4 7 7 7 4

```class Solution {
public:
int maxProfit(vector<int>& prices) {
int n = prices.size();
if (n < 2)return 0;
vector<int> minprice(n), maxprice(n);
for (int i = 0; i < n; ++i) {
minprice[i] = i == 0 ? INT_MAX : min(minprice[i - 1], prices[i - 1]);
maxprice[n - i - 1] = i == 0 ? INT_MIN : max(maxprice[n - i], prices[n - i]);
}
vector<int> profit1(n), profit2(n);
for (int i = 0; i < n; ++i) {
profit1[i] = i == 0 ? 0 : max(profit1[i - 1], prices[i] - minprice[i]);
profit2[n - i - 1] = i == 0 ? 0 : max(profit2[n - i], maxprice[n - i - 1] - prices[n - i - 1]);
}
int ans = 0;
for (int i = 0; i < n; ++i) {
ans = max(ans, profit1[i] + profit2[i]);
}
return ans;
}
};
```