Similar idea with Best Time to Buy and Sell Stock IV with DP


  • 0
    Z
    public int maxProfit(int[] prices) {
        if(prices.length < 2) return 0;
        int maxbuy = Math.max(-prices[0], -prices[1]);
        int[] dp = new int[prices.length];
        dp[0] = 0;
        dp[1] = Math.max(0, prices[1] - prices[0]);
        for(int i = 2; i < prices.length; i++){
            dp[i] = Math.max(dp[i-1], maxbuy + prices[i]);
            maxbuy = Math.max(maxbuy, dp[i-2] - prices[i]);
        }
        return dp[prices.length - 1];
    }

Log in to reply
 

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