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).

感觉此题太难,因为要求只能进行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;  
    }  
};

 

posted @ 2015-03-17 16:52  hongchun_z  阅读(143)  评论(0编辑  收藏  举报