6-line C++ solution


  • 0
    G
        int maxProfit(vector<int>& prices) {
            if (prices.size() <= 1) return 0;
            int bp = prices[0], profit = INT32_MIN;
            for (int i = 1; i < prices.size(); i++) {
                if (prices[i] < bp) bp = prices[i];
                else profit = max(profit, prices[i] - bp);
            }
            return (profit == INT32_MIN) ? 0 : profit;
        }
    

Log in to reply
 

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