leetcode 309. Best Time to Buy and Sell Stock with Cooldown

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 as many transactions as you like (ie, buy one and sell one share of the stock multiple times) with the following restrictions:

You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
After you sell your stock, you cannot buy stock on next day. (ie, cooldown 1 day)

Example:

prices = [1, 2, 3, 0, 2]
maxProfit = 3
transactions = [buy, sell, cooldown, buy, sell]

思路:dp[i][0]代表第i天清仓能得到的最大值,dp[i][1]表示第i天持仓能得到的最大值。
那么如果没有冷却期的话,dp[i][0]=max(dp[i-1][0],dp[i-1][1]+prices[i]),dp[i][1]=max(dp[i-1][1],dp[i-1][0]-prices[i]). 现在是有一天的冷却期,那么dp[i][1]=max(dp[i-1][1],dp[i-2][0]-prices[i]),即要保证今天持仓是由前天转移过来的。事实上前天dp[i-2][0]并不一定是清仓后的结果,也可能是根本没买,但(根本不买的这种情况)并不影响最后结果..

class Solution {
public:
    // 0
    int maxProfit(vector<int>& prices) {
        int n = prices.size();
        if (n == 0) return 0;
        vector<vector<int> > dp(n, vector<int>(2));
        int ans = 0;
        for (int i = 0; i < n; ++i) {
            if (i == 0) {
                dp[i][1] = -prices[i];
                dp[i][0] = 0;
            } else {
                //dp[i][1] = dp[i-1][1];
                dp[i][0] = max(dp[i-1][0], dp[i-1][1] + prices[i]); 
                if(i>=2) dp[i][1] = max(dp[i-1][1], dp[i-2][0] - prices[i]);
                else dp[i][1] = max(dp[i-1][1], dp[i-1][0] - prices[i]);
            }
        }
        return dp[n-1][0];
    }
};
posted on 2018-03-23 23:55  Beserious  阅读(144)  评论(0编辑  收藏  举报