309. The best time to buy and sell shares with the freezing of []

309. The best time to buy and sell shares with the freezing of


link

Title Description

Here Insert Picture Description

Thinking

Here Insert Picture Description

Code

class Solution {
    public int maxProfit(int[] prices) {
        if(prices == null || prices.length == 0){
            return 0;
        }
        int n = prices.length;
        int[][] dp = new int[n][2];
        for(int i = 0; i < n ;i++){
            if(i == 0){
                dp[i][0] = 0;
                //max(-infinity,-prices[i])
                dp[i][1] = -prices[i];
                continue;
            }
            if(i == 1){
                dp[i][0] = Math.max(dp[i-1][0],dp[i-1][1]+prices[i]);
                dp[i][1] = Math.max(-prices[0],-prices[1]);
                continue;
            }
        
            dp[i][0] = Math.max(dp[i-1][0],dp[i-1][1]+prices[i]);
            dp[i][1] = Math.max(dp[i-1][1],dp[i-2][0]-prices[i]);
        }
        return dp[n-1][0];
    }
}
Published 55 original articles · won praise 1 · views 862

Guess you like

Origin blog.csdn.net/weixin_42469108/article/details/105113348
Recommended