Accepted O(n) Java Solution with O(1) space


  • 1
    W
    public class Solution {
        public int maxProfit(int[] prices) {
            
            if(prices == null)return 0;
            if(prices.length < 2)return 0;
            
            int maxProfit = 0, min = prices[0], profitNow = 0;
            
            for(int i=1; i<prices.length; ++i){
                
                if(prices[i] > prices[i-1]){
                    profitNow = prices[i] - min;
                    maxProfit = profitNow > maxProfit ? profitNow : maxProfit;
                    
                }else{
                    
                    min = prices[i] < min ? prices[i] : min;
                }
                
            }
            
            return maxProfit;
            
        }
    }

Log in to reply
 

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