算法day36-动态规划(9)

目录

  1. 买卖股票的最佳时机IV
  2. 最佳买卖股票时机含冷冻期⭐⭐⭐
  3. 买卖股票的最佳时机含手续费

一、买卖股票的最佳时机IV

 https://leetcode.cn/problems/best-time-to-buy-and-sell-stock-iv/description/?envType=problem-list-v2&envId=8At1GmaZ

 

class Solution {
    public int maxProfit(int k, int[] prices) {
        int length = prices.length;
        int[][] dp = new int[length][2*k+1];
        for(int i=1; i<2*k; i+=2){
            dp[0][i] = -prices[0];
        }
        for(int i=1; i<length; i++){
            for(int j=0; j<2*k; j+=2){
                dp[i][j+1] = Math.max(dp[i-1][j+1], dp[i-1][j] - prices[i]);
                dp[i][j+2] = Math.max(dp[i-1][j+2], dp[i-1][j+1] + prices[i]);
            }
        }
        return dp[length-1][2*k];
    }
}

 

二、最佳买卖股票时机含冷冻期

 https://leetcode.cn/problems/best-time-to-buy-and-sell-stock-with-cooldown/description/?envType=problem-list-v2&envId=8At1GmaZ

 

class Solution {
    public int maxProfit(int[] prices) {
        //dp[i][0]:持有股票的状态
        //dp[i][1]: 保持卖出股票的状态(冷冻期之后的)
        //dp[i][2]: 卖出股票
        //dp[i][3]: 冷冻期(1天)
        //dp[i][0] : dp[i-1][0]保持前一天持有股票的状态
        //          dp[i-1][3]-prices[i]        前一天为冷冻期,第i天买入股票
        //          dp[i-1][1]-prices[i]        前一天为保持卖出股票的状态,第i天买入股票
        //dp[i][1]: dp[i-1][1]      前一天就是保持卖出股票的状态
        //          dp[i-1][3]      前一天是冷冻期
        //dp[i][2]: dp[i-1][0]+prices[i]        前一天是持有股票,第i天卖出股票
        //dp[i][3]: dp[i-1][2]         前一天刚卖出股票
        int[][] dp = new int[prices.length][4];
        dp[0][0] = -prices[0];      
        dp[0][1] = 0;       //如果根据定义看是一个非法状态,则根据递推公式看要初始化成什么
        dp[0][2] = 0;
        dp[0][3] = 0;
        for(int i=1; i<prices.length; i++){
            dp[i][0] = Math.max(dp[i-1][0], Math.max(dp[i-1][3]-prices[i],dp[i-1][1]-prices[i]));
            dp[i][1] = Math.max(dp[i-1][1], dp[i-1][3]);
            dp[i][2] = Math.max(dp[i-1][2], dp[i-1][0] + prices[i]);
            dp[i][3] = dp[i-1][2];
        }
        return Math.max(dp[prices.length-1][1],Math.max(dp[prices.length-1][2], dp[prices.length-1][3]));
    }
}

 

三、买卖股票的最佳时机含手续费

 https://leetcode.cn/problems/best-time-to-buy-and-sell-stock-with-transaction-fee/description/?envType=problem-list-v2&envId=8At1GmaZ

 

class Solution {
    public int maxProfit(int[] prices, int fee) {
        int length = prices.length;
        int[][] dp = new int[length][2];
        //在第0天持有股票的最大收益
        dp[0][0] = -prices[0]-fee;
        //在第0天不持股的最大收益
        dp[0][1] = 0;
        for(int i=1; i<length; i++){
            dp[i][0] = Math.max(dp[i-1][0], dp[i-1][1] - prices[i]-fee);
            dp[i][1] = Math.max(dp[i-1][1], dp[i-1][0] + prices[i]);
        }
        return dp[length-1][1];
    }
}

 

posted @ 2025-06-08 14:32  筱倩  阅读(17)  评论(0)    收藏  举报