代码随想录35期Day49-Java

Day49题目

LeetCode123买卖股票三

核心思想:和昨天的买卖股票相比,这个只允许买两次,因此把状态新增几个,可见代码注释

java 复制代码
class Solution {
    public int maxProfit(int[] prices) {
        // 设置五个状态  0 : 无操作 , 1 : 第一次买入, 2 : 第一次卖出 , 3: 第二次买入, 4:第二次卖出
        // 这几个状态都是持续性的,表示目前进行到了哪个阶段,而不是当前天的动作
        int[][] dp = new int[prices.length][5];
        dp[0][0] = 0 ;
        dp[0][1] = -prices[0];
        dp[0][2] = 0;
        dp[0][3] = -prices[0];
        dp[0][4] = 0;
        for(int i =  1 ; i < prices.length ; i ++){
            dp[i][0] = 0;
            dp[i][1] = Math.max(dp[i-1][1],dp[i-1][0]-prices[i]);
            dp[i][2] = Math.max(dp[i-1][2],dp[i-1][1]+prices[i]);
            dp[i][3] = Math.max(dp[i-1][3],dp[i-1][2]-prices[i]);
            dp[i][4] = Math.max(dp[i-1][4],dp[i-1][3]+prices[i]); 
        }
        return dp[prices.length-1][4];
    }
}

LeetCode188买卖股票四

核心思想:和上面题目不同的是,你最多可以买K次股票,因此需要有2*k+1个状态,选择奇数为买入,偶数为卖出

java 复制代码
class Solution {
    public int maxProfit(int k, int[] prices) {
        // 奇数为买入
        // 偶数为卖出
        int[][] dp = new int[prices.length][2*k+1];
        for(int i = 1 ; i < 2*k+1 ; i +=2){
            dp[0][i] = -prices[0]; 
        }
        for(int i = 1 ; i < prices.length ; i ++){
            for(int j  = 1; j < 2*k+1;  j +=2  ){
                dp[i][j] = Math.max(dp[i-1][j],dp[i-1][j-1] - prices[i]);
                dp[i][j+1] = Math.max(dp[i-1][j+1], dp[i-1][j] + prices[i]);
            }
        }
        return dp[prices.length-1][2*k];
    }
}
相关推荐
华科易迅5 分钟前
Spring 事务(注解)
java·数据库·spring
写代码的小阿帆8 分钟前
Web工程结构解析:从MVC分层到DDD领域驱动
java·架构·mvc
东离与糖宝30 分钟前
Java 26+Spring Boot 3.5,微服务启动从3秒压到0.8秒
java·人工智能
csdn_aspnet37 分钟前
C# 求n边凸多边形的对角线数量(Find number of diagonals in n sided convex polygon)
开发语言·算法·c#
禹中一只鱼1 小时前
【力扣热题100学习笔记】 - 哈希
java·学习·leetcode·哈希算法
凌波粒1 小时前
LeetCode--349.两个数组的交集(哈希表)
java·算法·leetcode·散列表
于先生吖1 小时前
Java+SpringBoot 无人健身房物联网系统完整源码实现
java·spring boot·物联网
johnrui1 小时前
SpringBoot-JdbcTemplate
java·spring boot·后端
码云社区1 小时前
JAVA二手车交易二手车市场系统源码支持微信小程序+微信公众号+H5+APP
java·开发语言·微信小程序·二手交易·闲置回收
crescent_悦1 小时前
C++:The Largest Generation
java·开发语言·c++