Self explanatory O(n) Java solution.


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

Log in to reply
 

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