Java 6 lines, 4 lines, 2 lines solutions


  • 18
    A

    I only count the new lines of code that I've written, i.e. everything except for the method definition and the method closing bracket.

    Proper Java - 6 lines:

    public int maxProfit(int[] prices) {
         int min = Integer.MAX_VALUE, max = 0;
         for (int i = 0; i < prices.length; i++) {
             min = Math.min(min, prices[i]);
             max = Math.max(max, prices[i] - min);
         }
         return max;
     }  
    

    Proper Java with shortcuts - 4 lines:

    public int maxProfit(int[] prices) {
        int min = Integer.MAX_VALUE, max = 0;
        for (int i = 0; i < prices.length; i++)
            max = Math.max(max, prices[i] - (min = Math.min(min, prices[i])));
        return max;
    }
    

    Java 8 streams - 2 lines:

    int min = Integer.MAX_VALUE;
    public int maxProfit(int[] prices) {
        return Arrays.stream(prices).map(i -> i - (min = Math.min(min, i))).max().orElse(0);
    }

  • 1
    Z

    Great, simple code :)
    java8 solution does not seem to be much readable.


  • 0
    Z

    thanks really nice try.


Log in to reply
 

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