C++ greedy solution, O(n) time & O(1) space


  • 0
    P
    int maxProfit(vector<int>& prices) {
        int buy = INT_MAX, profit = 0, profit_cd = 0;
        int n = prices.size();
        for (int i = 0; i < n; ++i) {
            int price = prices[i];
            buy = (i < 3)? min(price, buy): min(price - profit_cd, buy);
            profit_cd = profit;
            profit = max(profit, price - buy);
        }
        return profit;
    }

Log in to reply
 

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