Very simple Java O(n) solution


  • 0
    M
        public int maxProfit(int[] prices) {
            
            if(prices.length == 0) return 0;
            int max = 0; int buy = 0; int sell = 1;
            
            while(sell < prices.length){
                int diff = prices[sell] - prices[buy];
                if(diff < 0){
                   buy = sell;
                }else{
                   max = Math.max(diff, max);
                }
                sell++;
            }
            return max;
        }
    }
    

Log in to reply
 

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