Clean Java solution with O(n) time and O(1) space


  • 2
    C
    public int maxProfit(int[] prices) {
        if(prices.length < 2)
            return 0;
        int maxProf = 0;
        int min = 0, max = 0, prof;
        
        for(int i = 1; i < prices.length; ++i) {
            if(prices[i] < prices[min]) {
                min = i;
                max = max < min ? min : max;    // max keep up with min when get behind
            }
            
            if(prices[i] > prices[max])
                max = i;
                
            prof = prices[max] - prices[min];
            maxProf = prof > maxProf ? prof : maxProf;
        }
        
        return maxProf;
    }

Log in to reply
 

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