C++ O(1) Space, O(n) Time, 8 line, Clean and Short Solution w/ Comments.


  • 0
    F
    struct Solution {
        int maxProfit(vector<int>& prices) {
            ///max_buy_0, by today, the max profit you can make when your last action was BUY.
            ///max_buy_0 initially is INT_MIN, because this means you can't just sell at day 0.
            ///max_sell_0, by today, the max profit you can make when your last action was SELL.
            ///max_sell_1, by YESTERDAY, the max profit you can make when your last action was SELL.
            int max_buy_0 = INT_MIN, max_sell_0 = 0, max_sell_1 = 0;
            for (int i = 0 ; i < prices.size(); ++i)
            {
                max_buy_0 = max(max_sell_1 - prices[i], max_buy_0);
                max_sell_1 = max_sell_0;
                max_sell_0 = max(max_sell_0, max_buy_0 + prices[i]);
            }
            return max_sell_0;
        }
    };
    

Log in to reply
 

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