Easy to understand 6 line Java solution


  • 0
    T

    All you have to track is the minimum stock price and the maximum profit that can be generated. This is an O(n) solution with O(1) space and you can't do better than this in terms of complexity.

    public int maxProfit(int[] prices) {
        
        //Trivial cases
        if(prices.length <= 1) { return 0;}
        
        int maxProfit = 0, minStock = prices[0];
        for(int currentPrice : prices) {
            if(currentPrice < minStock) { minStock = currentPrice;}
            if(currentPrice - minStock > maxProfit) { maxProfit = currentPrice - minStock;}
        }
        return maxProfit;
    }

Log in to reply
 

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