This is my simple java solution with O(n) time complexity and O(1) space


  • 0
    R
     public int maxProfit(int[] prices) {
        if(prices == null || prices.length <= 1)
        return 0;
        
        int min_ele = prices[0];
        int profit =0;
        for(int i =1; i < prices.length; i++){
            if(prices[i] - min_ele > profit)
               profit = prices[i] - min_ele;
               
            else if(prices[i] < min_ele)
             min_ele = prices[i];
        }
        
        return profit;
    }

Log in to reply
 

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