Say you have an array for which the *i*th 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).

Find the maximum profit, it must be a DP problem.

We can use two pointers, one forward, and the other backward. The first pointer means we bought the stock some day before, and we sell it now; the second pointer means we buy the stock now, and will sell it some day later. So the only thing we need to do is build two arrays, and find one day that the sum of the profit in these two arrays is maximum.

Using DP, the code is really simple.

int maxProfit(vector<int> &prices) { if (prices.size() == 0) return 0; vector<int> forward(prices.size()); vector<int> backward(prices.size()); int minV = prices[0]; forward[0] = 0; for(int i = 1; i < prices.size(); i++){ minV = min(minV, prices[i]); forward[i] = max(forward[i-1], prices[i] - minV); } int maxV = prices[prices.size()-1]; backward[backward.size()-1] = 0; for(int i = prices.size() - 2; i >= 0; i--){ maxV = max(prices[i], maxV); backward[i] = max(backward[i+1], maxV - prices[i]); } int sum = 0; for(int i = 0; i < prices.size(); i++) sum = max(sum, forward[i] + backward[i]); return sum; }

🙂