Day42 >> 188、买卖股票的最佳时机IV + 309.最佳买卖股票时机含冷冻期 + 714.买卖股票的最佳时机含手续费

代码随想录-动态规划Part9

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

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

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

java 复制代码
class Solution {
    public int maxProfit(int[] prices) {
        if (prices == null || prices.length < 2) {
            return 0;
        }
        int[][] dp = new int[prices.length][2];

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

        for (int i = 2; i < prices.length; i++) {
            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[prices.length - 1][0];
    }
}

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

java 复制代码
class Solution {
    public int maxProfit(int[] prices, int fee) {
        int dp[][] = new int[2][2];
        int len = prices.length;
        dp[0][0] = -prices[0];

        for(int i = 1; i < len; i++){
            dp[i % 2][0] = Math.max(dp[(i - 1) % 2][0], dp[(i - 1) % 2][1] - prices[i]);
            dp[i % 2][1] = Math.max(dp[(i - 1) % 2][1], dp[(i - 1) % 2][0] + prices[i] - fee);
        }

        return dp[(len - 1) % 2][1];
    }
}
相关推荐
wu_asia1 小时前
方阵对角线元素乘积计算
数据结构·算法
想逃离铁厂的老铁2 小时前
Day43 >> 300.最长递增子序列 + 674. 最长连续递增序列+ 718. 最长重复子数组
数据结构·算法
Yzzz-F2 小时前
P6648 [CCC 2019] Triangle: The Data Structure [st表]
算法
LateFrames2 小时前
泰勒级数:从 “单点” 到 “理论与实践的鸿沟”
学习·算法
武帝为此2 小时前
【RC4加密算法介绍】
网络·python·算法
宵时待雨2 小时前
数据结构(初阶)笔记归纳4:单链表的实现
c语言·开发语言·数据结构·笔记·算法
Hacker_xingchen3 小时前
如何用Postman做接口自动化测试及完美的可视化报告?
自动化测试·软件测试·测试工具·职场和发展·postman
BLSxiaopanlaile3 小时前
关于子集和问题的几种解法
数据结构·算法·剪枝·回溯·分解
狐573 小时前
2026-01-17-LeetCode刷题笔记-3047-求交集区域内的最大正方形面积
笔记·算法·leetcode