https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/

Source


    int maxProfit(vector<int>& prices) {
        const int NUM_TRS = 2;
        const int MAX = static_cast<int>(1e5);
        int position[NUM_TRS] = {MAX, MAX};
        int profit[NUM_TRS] = {0, 0};
        FOR (i, prices.size()) {
            position[0] = min(position[0], prices[i]);
            profit[0] = max(profit[0], prices[i]-position[0]);   // profit[0] = prices[i] - position[0]
            position[1] = min(position[1], (-profit[0] + prices[i]));
            profit[1] = max(profit[1], prices[i]-position[1]);   // profit[1] = prices[i] - (bought[1] - profit[0])
        }
        return profit[1];
    }

GitHub

MaxProfit3