4 lines c++, O(n) time, O(1) space


  • 0
    int maxProfit(vector<int>& prices) {
        vector<int> s{0, INT_MIN, 0};
        for (int i : prices)
            s = {max(s[0], s[2]), max(s[0] - i, s[1]), s[1] + i};
        return max(s[0], s[2]);
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.