DP solution, O(n) time, O(1) space


  • 1
    P
    class Solution {
    public:
        int maxProfit(vector<int>& prices) {
            if (prices.empty()) {
                return 0;
            }
            int buy[2] = {0, 0};
            int sell = 0;
            for (int i = prices.size() - 1; i >= 0; --i) {
                int b = max(sell - prices[i], buy[0]);
                sell = max(prices[i] + buy[1], sell);
                buy[1] = buy[0];
                buy[0] = b;
            }
            return buy[0];
        }
    };

Log in to reply
 

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