Leetcode 题解 - 动态规划-股票交易(4): 只能进行 k 次的股票交易

[LeetCode] Best Time to Buy and Sell Stock IV 买卖股票的最佳时间之四

这个题只考虑 n-1天 也就是第二天到最后一天 只计算差值

而且, j从最大值开始k 因为从0 开始很多值都越界 而且最大值算的之后不会被覆盖

global是今天亏的情况 

local

Say you have an array for which the ith element is the price of a given stock on day i.

Design an algorithm to find the maximum profit. You may complete at most k transactions.

Note:
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

Credits:
Special thanks to @Freezen for adding this problem and creating all test cases.

 

这道题实际上是之前那道 Best Time to Buy and Sell Stock III 买股票的最佳时间之三的一般情况的推广,还是需要用动态规划Dynamic programming来解决,具体思路如下:

这里我们需要两个递推公式来分别更新两个变量local和global,参见网友Code Ganker的博客,我们其实可以求至少k次交易的最大利润。我们定义local[i][j]为在到达第i天时最多可进行j次交易并且最后一次交易在最后一天卖出的最大利润,此为局部最优。然后我们定义global[i][j]为在到达第i天时最多可进行j次交易的最大利润,此为全局最优。它们的递推式为:

local[i][j] = max(global[i - 1][j - 1] + max(diff, 0), local[i][j] + diff)

global[i][j] = max(local[i][j], global[i - 1][j]),

其中局部最优值是比较前一天并少交易一次的全局最优加上大于0的差值,和i天进行 j 次交易且今天卖最优加上差值后相比,两者之中取较大值,而全局最优比较局部最优和前一天的全局最优。

但这道题还有个坑,就是如果k的值远大于prices的天数,比如k是好几百万,而prices的天数就为若干天的话,上面的DP解法就非常的没有效率,应该直接用Best Time to Buy and Sell Stock II 买股票的最佳时间之二的方法来求解,所以实际上这道题是之前的二和三的综合体,代码如下:

 

class Solution {
    public int maxProfit(int k, int[] prices) {
        if(k >= prices.length) //如果大于长度要求的天数 那么我们直接比大小就行了
            return resovle(prices);
        int[] local = new int[k+1];
        int[] global = new int[k+1]; 
        for(int i = 0; i < prices.length - 1; i++){
            int diff = prices[i+1] - prices[i];
            for(int j = k; j > 0; j--){
                local[j] = Math.max(global[j - 1] + (diff > 0 ? diff : 0), 
                                   local[j] + diff);
                global[j] = Math.max(global[j], local[j]);
            
            }
        }
        return global[k];
    }
    private int resovle(int[] prices){
        int res = 0;
        for(int i = 1; i < prices.length; i++){
            if(prices[i] - prices[i - 1] > 0)
                res += prices[i] - prices[i - 1];
        }
        return res;
    }
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值