188. Best Time to Buy and Sell Stock IV (Array; DP)

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

思路:用状态存储至当前日为止第jth buy/sell的最大利润。到了第二天,我们可以按j从大到小(因为j大的新状态依赖于之前j小的状态),修改这个状态。

class Solution {
public:
    int maxProfit(int k, vector<int>& prices) {
        int dates = prices.size();
        if(dates <= 1 || k == 0) return 0;
        if (k >= prices.size()) return maxProfit2(prices); //unlimited transaction
        
        vector<int> release(k,0); //sell stock
        vector<int> hold(k,INT_MIN); //buy stock
        
        for(int i = 0; i < dates; i++){
            for(int j = k-1; j > 0; j--){
                release[j] = max(release[j], hold[j]+prices[i]); //jth sell happen at ith day 
                hold[j]=max(hold[j], release[j-1]-prices[i]); //jth buy happen at ith day
            }
            release[0] = max(release[0], hold[0]+prices[i]);
            hold[0] = max(hold[0],-prices[i]);
        }
        return release[k-1];
    }
    
    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;
    }
};

 

posted on 2015-12-16 08:46  joannae  阅读(132)  评论(0编辑  收藏  举报

导航