8ms, one-pass, cpp solution


  • 0
    O
    class Solution {
    public:
        int maxProfit(vector<int>& prices) {
            if (prices.empty()) return 0;
            int ans = 0, min_val = prices[0];
            for (int i = 1; i < prices.size(); i++) min_val = min(min_val, prices[i - 1]), ans = max(ans, prices[i] - min_val);
            return ans;
        }
    };

Log in to reply
 

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