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

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

时间:2015-12-16 09:35:09      阅读:194      评论: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).

思路:用状态存储至当前日为止第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;
    }
};

 

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

标签:

原文地址:http://www.cnblogs.com/qionglouyuyu/p/5050075.html

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