LeetCode: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.

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

思路:

  这道题与上次的Best time to Buy and Sell Stock III 的不同之处在于这次的最大交易次数不再是2,而是k,所有不能再用我前面两篇博客所用的方法了。
  这次仍然使用动态规划来解题,用的是“局部最优和全局最优法”。我们需要维护两个变量,local[i][j]为在到达第i天时最多进行j次交易且第j次交易在第i天卖出的最大利润,此为局部最优;global[i][j]为在到达第i天时最多可进行j次交易的最大利润,此为全局最优。
  显然,全局的递推式为global[i][j]=max(local[i][j], global[i-1][j]);局部的递推式为local[i][j]=max(global[i-1][j-1]+max(diff,0), local[i-1][j]+diff),第一个量全局到达i-1天进行j-1次交易,那么第j次的交易可以是第i-1天买进,第i天卖出(利润为diff),也可以是第i天买进且卖出(利润为0),所以两者之中取最大;第二个量则是取local第i-1天进行j次交易,因为要第i天进行第j次交易,所以只需要把原来是第i-1天卖出的交易改成第i天才卖出,即加上差价diff。
  本题有一种特殊情况,就是如果k的值远大于prices的天数,用上面的方法效率很低,需要改进。这种情况相当于交易次数不限,那么只要后一天与前一天的差价大于0,就可以进行交易了。
  

代码:

class Solution {
public:
    int maxProfit(int k, vector<int>& prices) {
        if (prices.size() == 0) return 0;
        if (prices.size() <= k) return maxmaxProfit(prices);
        int local[k+1] = {0};
        int global[k+1] = {0};
        for (int i = 0; i < prices.size()-1; i++) {
            int diff = prices[i+1] - prices[i];
            for (int j = k; j >= 1; j--) {
                local[j] = max(global[j-1] + max(diff, 0), local[j]+diff);
                global[j] = max(global[j], local[j]);
            }
        }
        return global[k];
    }

    int maxmaxProfit(vector<int>& prices) {
        int profit = 0;
        for (int i = 1; i < prices.size(); i++) {
            if (prices[i] - prices[i-1] > 0) {
                profit += prices[i] - prices[i-1];
            }
        }
        return profit;
    }
};

时间复杂度:O(n*k)

参考博客:
http://blog.csdn.net/linhuanmars/article/details/23236995
http://www.cnblogs.com/grandyang/p/4295761.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值