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

121. 买卖股票的最佳时机

视频讲解:动态规划之 LeetCode:121.买卖股票的最佳时机1_哔哩哔哩_bilibili

代码随想录

class Solution {
    public int maxProfit(int[] prices) {
        int minPurchasePrice = Integer.MAX_VALUE;
        int result = 0;
        for(int j = 0; j < prices.length; j++){
            minPurchasePrice = Math.min(prices[j], minPurchasePrice);
            result = Math.max(prices[j] - minPurchasePrice, result);
        }
        return result;
    }
}

122.买卖股票的最佳时机II

视频讲解:动态规划,股票问题第二弹 | LeetCode:122.买卖股票的最佳时机II_哔哩哔哩_bilibili

代码随想录

class Solution {
    public int maxProfit(int[] prices) {
        int length = prices.length;
        int[][] profitMatrix = new int[length][2];
        profitMatrix[0][0] = 0;
        profitMatrix[0][1] = -prices[0];
        for (int day = 1; day < 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 - 1][0] - prices[day]);
        }
        return profitMatrix[length - 1][0];
    }
}

123.买卖股票的最佳时机III

这道题一下子就难度上来了,关键在于至多买卖两次,这意味着可以买卖一次,可以买卖两次,也可以不买卖。

视频讲解:动态规划,股票至多买卖两次,怎么求? | LeetCode:123.买卖股票最佳时机III_哔哩哔哩_bilibili

代码随想录

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

        int[][] profitMatrix = new int[length][5];
        profitMatrix[0][1] = -prices[0];
        profitMatrix[0][3] = -prices[0];

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

        return profitMatrix[length - 1][4];
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值