Pretty simple Java solution ( 6 lines with no abbreviation )


  • 0
    J
    public int maxProfit(int[] prices) {
        int profit = 0;
        for (int i = 1; i < prices.length; i++) {
            int profitToday = prices[i] - prices[i - 1];
            profit += profitToday > 0 ? profitToday : 0;
        }
        return profit;
    }

  • 0
    P

    concise and pretty well


  • 0
    M

    Looks like that solution fails to this invariant:
    However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again)
    since you are buying and selling on the same day


Log in to reply
 

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