代码随想录算法训练营第42天

188.买卖股票的最佳时机IV

本题是123.买卖股票的最佳时机III 的进阶版

视频讲解:动态规划来决定最佳时机,至多可以买卖K次!| LeetCode:188.买卖股票最佳时机4_哔哩哔哩_bilibili

代码随想录

class Solution {
    public int maxProfit(int k, int[] prices) {
        if (prices.length == 0) return 0;

        int length = prices.length;
        int[][][] profitMatrix = new int[length][k + 1][2];

        for (int transaction = 0; transaction <= k; transaction++) {
            profitMatrix[0][transaction][1] = -prices[0];
        }

        for (int day = 1; day < length; day++) {
            for (int transaction = 1; transaction <= k; transaction++) {
                profitMatrix[day][transaction][0] = Math.max(profitMatrix[day - 1][transaction][0], profitMatrix[day - 1][transaction][1] + prices[day]);
                profitMatrix[day][transaction][1] = Math.max(profitMatrix[day - 1][transaction][1], profitMatrix[day - 1][transaction - 1][0] - prices[day]);
            }
        }
        return profitMatrix[length - 1][k][0];
    }
}

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

本题加了一个冷冻期,状态就多了,有点难度,大家要把各个状态分清,思路才能清晰

视频讲解:动态规划来决定最佳时机,这次有冷冻期!| LeetCode:309.买卖股票的最佳时机含冷冻期_哔哩哔哩_bilibili

代码随想录

class Solution {
    public int maxProfit(int[] prices) {
        if (prices == null || prices.length < 2) {
            return 0;
        }
        int[][] profitMatrix = new int[prices.length][2];

        profitMatrix[0][0] = 0;
        profitMatrix[0][1] = -prices[0];
        profitMatrix[1][0] = Math.max(profitMatrix[0][0], profitMatrix[0][1] + prices[1]);
        profitMatrix[1][1] = Math.max(profitMatrix[0][1], -prices[1]);

        for (int day = 2; day < prices.length; day++) {
            profitMatrix[day][0] = Math.max(profitMatrix[day - 1][0], profitMatrix[day - 1][1] + prices[day]);
            profitMatrix[day][1] = Math.max(profitMatrix[day - 1][1], profitMatrix[day - 2][0] - prices[day]);
        }

        return profitMatrix[prices.length - 1][0];
    }
}

714.买卖股票的最佳时机含手续费

相对122.买卖股票的最佳时机II ,本题只需要在计算卖出操作的时候减去手续费就可以了,代码几乎是一样的,可以尝试自己做一做。

视频讲解:动态规划来决定最佳时机,这次含手续费!| LeetCode:714.买卖股票的最佳时机含手续费_哔哩哔哩_bilibili

代码随想录

class Solution {
    public int maxProfit(int[] prices, int fee) {
        int[][] profitMatrix = new int[2][2];
        int length = prices.length;
        profitMatrix[0][0] = -prices[0];

        for (int day = 1; day < length; day++) {
            profitMatrix[day % 2][0] = Math.max(profitMatrix[(day - 1) % 2][0], profitMatrix[(day - 1) % 2][1] - prices[day]);
            profitMatrix[day % 2][1] = Math.max(profitMatrix[(day - 1) % 2][1], profitMatrix[(day - 1) % 2][0] + prices[day] - fee);
        }

        return profitMatrix[(length - 1) % 2][1];
    }
}

股票总结

股票问题做一个总结吧

代码随想录

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值