首页 > 其他 > 详细

Best Time to Buy and Sell Stock IV -- leetcode

时间:2015-03-27 17:36:35      阅读:517      评论:0      收藏:0      [点我收藏+]

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

Best Time to Buy and Sell Stock IV -- leetcode

原文:http://blog.csdn.net/elton_xiao/article/details/44676957

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!