动态规划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();
    }
}
相关推荐
心中有国也有家2 小时前
cann-recipes-infer:昇腾 NPU 推理的“菜谱集合”
经验分享·笔记·学习·算法
绝知此事2 小时前
【算法突围 01】线性结构与哈希表:后端开发的收纳术
java·数据结构·算法·面试·jdk·散列表
碧海银沙音频科技研究院2 小时前
通话AEC与语音识别AEC的软硬回采链路
深度学习·算法·语音识别
csdn_aspnet3 小时前
Python 算法快闪 LeetCode 编号 70 - 爬楼梯
python·算法·leetcode·职场和发展
m0_629494736 小时前
LeetCode 热题 100-----26.环形链表 II
数据结构·算法·leetcode·链表
壹号用户6 小时前
用队列实现栈
数据结构·算法
做人求其滴6 小时前
面试经典 150 题 380 274
c++·算法·面试·职场和发展·力扣
daad7776 小时前
记一组无人机IMU传感器数据
算法
计算机安禾6 小时前
【c++面向对象编程】第42篇:模板特化与偏特化:为特定类型定制实现
开发语言·c++·算法