day51|● 309.最佳买卖股票时机含冷冻期 ● 714.买卖股票的最佳时机含手续费

309.最佳买卖股票时机含冷冻期

这题我一开始的想法是,冷冻期代表着买入股票时受限,需要从i-2天的not hold来考虑购买。

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

这是细分了状态转移,尤其是not hold stock时的,刚卖出,冷冻期,持续not hold
在这里插入图片描述
具体可以区分出如下四个状态:

状态一:持有股票状态(今天买入股票,或者是之前就买入了股票然后没有操作,一直持有)

不持有股票状态
状态二:保持卖出股票的状态(两天前就卖出了股票,度过一天冷冻期。或者是前一天就是卖出股票状态,一直没操作)
状态三:今天卖出股票
状态四:今天为冷冻期状态,但冷冻期状态不可持续,只有一天!

class Solution {
    public int maxProfit(int[] prices) {
        // 0: hold stock
        // 1: sold today
        // 2: cooldown
        // 3: not hold stock and no other status
        int[][] dp = new int[prices.length][4];
        dp[0][0] = -prices[0];
        for (int i = 1; i < prices.length; i++) {
            dp[i][0] = Math.max(dp[i-1][0], Math.max(dp[i-1][2]-prices[i], dp[i-1][3]-prices[i]));
            dp[i][1] = dp[i-1][0]+prices[i];
            dp[i][2] = dp[i-1][1];
            dp[i][3] = Math.max(dp[i-1][2], dp[i-1][3]);
        }
        return Math.max(dp[dp.length-1][1], Math.max(dp[dp.length-1][2], dp[dp.length-1][3]));
    }
}

时间复杂度:O(n)
空间复杂度:O(n)

● 714.买卖股票的最佳时机含手续费
与ii和相似,只是多了一步需要在卖出时,减去手续费

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

时间复杂度:O(n)
空间复杂度:O(n)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值