6 line Java with explanations


  • 0
    S

    class Solution {

    public int maxProfit(int[] prices) {
        int profit1=0, profit2=0, max = 0;
        for(int i=1; i<prices.length; i++){
            profit1=Math.max(profit1+prices[i]-prices[i-1], profit2);
            profit2 = max;
            max = Math.max(profit1, max);
            // System.out.println("i: " + i + "   max: " + max + "  profit1: " + profit1 + "   profit2: " + profit2);
        }
        return max;
    }
    

    }

    (1). profit1 is buy the previous day and sell
    (2). profit 2 is doing nothing, and thus the max profit of yesterday
    (3). Buy 1 sell 10 is the same as Buy 1 sell 2 and buy 2 sell 10.
    [1,2,10]
    (4). If you don't understand, printout the values with test case [1, 2, 10]

    /* me: Buy 1 sell 10 is the same as Buy 1 sell 2 and buy 2 sell 10.
    [1,2,10]

    Your stdout

    i: 1 max: 1 profit1: 1 profit2: 0
    i: 2 max: 9 profit1: 9 profit2: 0 //

    Your answer

    9
    */


Log in to reply
 

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