123. Best Time to Buy and Sell Stock III

class Solution {
public:
    int maxProfit(vector<int>& prices)
    {
    int t1minCost = INT_MAX, t2minCost = INT_MAX;
    int t1maxProfit = 0, t2maxProfit = 0;

    for (int price : prices)
    {
        t1minCost = min(t1minCost, price);
        t1maxProfit = max(t1maxProfit, price - t1minCost);
        t2minCost = min(t2minCost, price - t1maxProfit);
        t2maxProfit = max(t2maxProfit, price - t2minCost);
    }
    return t2maxProfit;
    }
};
  • T: O(N)O(N)
  • S: O(1)O(1)