动态规划31(Leetcode188买卖股票的最佳时机4)

代码:

我的状态方程:

buy[i][j]=max{buy[i−1][j],sell[i−1][j-1]−price[i]}

题解里的:

buy[i][j]=max{buy[i−1][j],sell[i−1][j]−price[i]}

..没理解题解的 但我的通过了

java 复制代码
class Solution {
    public int maxProfit(int k, int[] prices) {
        if(prices.length==0)return 0;
        int n = prices.length;
        k = Math.min(k,n/2);
        if(k==0)return 0;
        int[][] buy = new int[n][k];
        int[][] sell = new int[n][k];
        buy[0][0]=-prices[0];
        sell[0][0]=0;
        for(int i=1;i<k;i++){
            buy[0][i] = sell[0][i] = Integer.MIN_VALUE / 2;
        }
        for(int i=1;i<n;i++){
            buy[i][0] = Math.max(buy[i-1][0],-prices[i]);
            sell[i][0] = Math.max(sell[i-1][0],buy[i-1][0]+prices[i]);
            for(int j=1;j<k;j++){
                buy[i][j] = Math.max(sell[i-1][j-1]-prices[i],buy[i-1][j]);
                sell[i][j] = Math.max(buy[i-1][j]+prices[i],sell[i-1][j]);
            }
        }
        return Arrays.stream(sell[n-1]).max().getAsInt();
    }
}
相关推荐
米粒128 分钟前
力扣算法刷题 Day 27
算法·leetcode·职场和发展
Fuxiao___1 小时前
C 语言核心知识点讲义(循环 + 函数篇)
算法·c#
漫随流水2 小时前
c++编程:反转字符串(leetcode344)
数据结构·c++·算法
穿条秋裤到处跑3 小时前
每日一道leetcode(2026.03.31):字典序最小的生成字符串
算法·leetcode
CoovallyAIHub5 小时前
VisionClaw:智能眼镜 + Gemini + Agent,看一眼就能帮你搜、帮你发、帮你做
算法·架构·github
CoovallyAIHub6 小时前
低空安全刚需!西工大UAV-DETR反无人机小目标检测,参数减少40%,mAP50:95提升6.6个百分点
算法·架构·github
CoovallyAIHub6 小时前
IEEE Sensors | 湖南大学提出KGP-YOLO:先定位风电叶片再检测缺陷,三数据集mAP均超87%
算法
Yupureki6 小时前
《算法竞赛从入门到国奖》算法基础:动态规划-路径dp
数据结构·c++·算法·动态规划
副露のmagic6 小时前
数组章节 leetcode 思路&实现
算法·leetcode·职场和发展
荣光属于凯撒6 小时前
P2176 [USACO11DEC] RoadBlock S / [USACO14FEB] Roadblock G/S
算法·图论