码迷,mamicode.com
首页 > 其他好文 > 详细

Best Time to Buy and Sell Stock IV

时间:2015-03-17 17:47:37      阅读:140      评论: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).

感觉此题太难,因为要求只能进行k次买卖,所以在考虑波峰,波谷的基础上要考虑买卖的次数,网上只找到了c++版的,运行了一下,可以正确运行。

 

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

 

Best Time to Buy and Sell Stock IV

标签:

原文地址:http://www.cnblogs.com/zhhc/p/4344821.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!