Simple 4-line Solution - Sorry angie yunqi! :D


  • 8
    G
    public int maxProfit(int[] prices) {
        int result = 0;
        for (int i = 1; i < prices.length; i++)
            result += Math.max(prices[i] - prices[i - 1], 0);
        return result;
    }

  • -3
    A

    Had to do some magic but made it 3 lines :D

    public int maxProfit(int[] prices) {
        for (int i = 1; i < prices.length; i++) 
            prices[i-1] = Math.max(0,prices[i] - prices[i-1]) + (i == 1 ? 0 : prices[i-2]);
        return prices.length < 2 ? 0 : prices[prices.length - 2];
    }

Log in to reply
 

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