My Java solution; actually the array is not necessary, but it is easier to code


  • 0
    V
    public int maxProfit(int[] prices) {
        int len = prices.length;
        int[] buy = new int[len+1];
        int[] sell = new int[len+1];
        for (int i=1;i<=len;i++) {
            if (i == 1) {
                buy[i] = -prices[i-1];
                sell[i] = 0;
            } else {
                buy[i] = Math.max(sell[i - 2] - prices[i-1], buy[i - 1]);
                sell[i] = Math.max(sell[i - 1], buy[i - 1] + prices[i-1]);
            }
    
        }
        return sell[len];
    }

Log in to reply
 

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