Best Time to Buy and Sell Stock IV -- leetcode

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.


class Solution {
public:
    int maxProfit(int k, vector<int> &prices) {
        if (k >= prices.size())
            return maxProfit2(prices);
            
        vector<int> release(k+1);
        vector<int> hold(k, INT_MIN);
        
        for (auto p: prices) {
            for (int i=0; i<k; i++) {
                release[i] = max(release[i], hold[i]+p);
                hold[i] = max(hold[i], release[i+1]-p);
            }
        }
        
        return release[0];
    }
    
    int maxProfit2(vector<int> &prices) {
        int profit = 0;
        for (int i=0; i<(int)prices.size()-1; i++) {
            if (prices[i+1] > prices[i])
                profit += prices[i+1] - prices[i];
        }
        
        return profit;
    }
};


此题思路借鉴之以下leetcode讨论:

https://leetcode.com/discuss/18330/is-it-best-solution-with-o-n-o-1

该讨论是针对交易次数为2次的的情况。

但思路是一样的。我将其扩充到任意次数的情况。


需要注意的事,test case中,有一个非常大的k值,直接会让内存分配失败。

如何处理该种情况呢。 当k值超过prices值的个数时,此时,可以把问题转换为交易数次不限的情况。即

Best Time to Buy and Sell Stock II


另一篇博文也很好的介绍了这个问题的解法。这两者的思路其实是一样的。

参见:http://blog.csdn.net/linhuanmars/article/details/23236995

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值