Best Time to Buy and Sell Stock IV

leetcode中的股票问题(4)

第四题还是有点难的,特别是在连续完成前3题后,思路可能就顿时局限了,主要参考别人的实现,我这里做一些分析。
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/

原题

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.
翻译:和前一题基本一样,只是从最多2手交易改成了最多k手交易。

问题分析

这里我的直觉就是用动态规划来解决这个问题,但是具体怎么做呢?
很容易想到的就是维护变量 profit(i,j) ,这里 i j表示在i天最多做j手交易。
profit(i,j)=Max(profit(i1,j),profitAt(i,j))
其中 profitAt(i,j) 表示,在第i天一定要发生交易的情况下最多做j手交易的最大收益(有点拗口,吼吼吼),因为这样才能对 profit(i,j) 做一个合理的划分。
profitAt(i,j) 呢?怎么递推呢?
我们说 profitAt(i,j)=Max(profit(i1,j1)+Max(0,diff),profitAt(i1,j)+diff) ,其中 diff=price(i)price(i1)
怎么理解呢,同样是要做一个划分,既然第i天必定有交易(必定有卖出行为),那我对这一手的买进时间做这样划分:买进时间 >=i1 或者 <i1 <script type="math/tex" id="MathJax-Element-14"> >=i1 的情况,在 i1 天之前就完成 j1 手交易,而最后一次买卖的收益是 Max(0,diff) ;对于 <i1 <script type="math/tex" id="MathJax-Element-19"> profitAt(i1,j)+diff) 来递推,直接加上 diff 的原因是将原本在第 i1 天卖掉的股票移到第i天卖掉,直接加上这两天的差价就行!
然后就很简单了,直接上代码。
下面的代码中 global就是profit()函数,而local就是profitAt()函数。

代码

public int maxProfit(int k, int[] prices) {
    if(prices==null || prices.length==0)
            return 0;
    //如果k>一半天数,问题退化成问题(3)了
    if(k > prices.length/2)
    {
        int sum =0;
        for(int i = 0 ; i < prices.length-1 ; i++)
        {
            int gain = prices[i+1] - prices[i];
            if(gain > 0)
                sum += gain;
        }
        return sum;
    }

    int[][] global=new int[prices.length][k+1];
    int[][] local=new int[prices.length][k+1];
    for(int i=0;i<prices.length-1;i++)
    {
        int diff=prices[i+1]-prices[i];
        for(int j=0;j<=k-1;j++)
        {
            local[i+1][j+1]=Math.max(global[i][j]+Math.max(diff,0),local[i][j+1]+diff);
            global[i+1][j+1]=Math.max(global[i][j+1],local[i+1][j+1]);
        }
    }
    return global[prices.length-1][k];
}

接下来我们会去看看在leetcode中和数组以及链表的“rotate”操作相关的几个问题~

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值