216ms Java Splution O(n)


  • 0
    E

    public class Solution {
    public int maxProfit(int[] prices) {

        if (prices == null || prices.length <2) { return 0;}
    
        int[] priceDiff = new int[prices.length - 1]; 
        for (int i = 0 ; i < prices.length -1; i++){
            priceDiff[i] = prices[i+1] - prices[i]; 
        }
        
        int MaxSum = priceDiff[0]; 
        int currentSum = 0;
        
        for (int j = 0; j < priceDiff.length; j++){
            currentSum += priceDiff[j]; 
            if (MaxSum < currentSum) MaxSum = currentSum;
            if (currentSum <0) currentSum = 0; 
        }
        
        return Math.max(MaxSum,0);
    }
    

    }


Log in to reply
 

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