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:

Input: [1,2,3,0,2]
Output: 3 
Explanation: transactions = [buy, sell, cooldown, buy, sell]

sell是今天手里没有股票,sell[i] 的第一种可能:今天没动作跟昨天持股状态一样,也可以看作是前天卖了之后的cooldown期(也可能是股票价格高一直没买),总之今天妹有。第二种:股票是今天卖的,buy[i - 1] + prices[i], buy[i - 1]是前一天持股的最大利润,因为前一天持股,所以今天才有的卖。

buy是今天手里有股票,可能是今天买的也可能是之前买的。buy[i]的第一种可能:buy[i - 1](昨天手里也有股票,今天啥都没干),第二种可能:sell[i - 2] - prices[i](前天卖了经过一天空窗期,今天买了股票)。

class Solution {
    public int maxProfit(int[] prices) {
        int k = prices.length;
        if (k==0) return 0;
        
        int[] sell = new int[k];
        int[] buy = new int[k];
        sell[0] = 0;
        buy[0] = -prices[0];
        
        for(int i = 1; i < k; i++){
            sell[i] = Math.max(sell[i-1], buy[i-1] + prices[i]);
            buy[i] = Math.max(buy[i-1], (i > 1 ? sell[i-2] : 0) - prices[i]);
        }
        return sell[k-1];
    }
}

初始值sell为0,意思是第一天卖掉的利润(买了再卖肯定是0)

buy为-prices[0],意思是第一天买了的利润(肯定是-prices[0])。

原文地址:https://www.cnblogs.com/wentiliangkaihua/p/11653207.html