8 lines java O(n) solution


  • 0
    N

    We iterate right to left,computing the difference each time and assigning the max value to a variable.
    after that we check max value;

    public int maxProfit(int[] prices) {
            if(prices.length<2)
            return 0;
            int maxDiff=0,max=prices[prices.length-1];
            for(int k=prices.length-1;k>=0&&prices.length>=2;k--){
                maxDiff = Math.max(max-prices[k],maxDiff);
                max = Math.max(max,prices[k]);
            }
            return maxDiff;
        }
    

Log in to reply
 

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