309. Best Time to Buy and Sell Stock with Cooldown - jiejackyzhang/leetcode-note GitHub Wiki
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]
解题思路为Dynamic Programming。
在第i天有三种状态,buy,sell,rest,分别记录三种状态下的max profit。
buy[i] = max(buy[i-1], rest[i-1]-prices[i]) sell[i] = buy[i-1] + prices[i] rest[i] = max(rest[i-1], sell[i-1])
base cases为
buy[0] = -prices[0] sell[0] = MIN_VALUE rest[0] = 0
public class Solution {
    public int maxProfit(int[] prices) {
        if(prices == null || prices.length == 0) return 0;
        int n = prices.length;
        int[] buy = new int[n];
        int[] sell = new int[n];
        int[] rest = new int[n];
        buy[0] = -prices[0];
        sell[0] = Integer.MIN_VALUE;
        rest[0] = 0;
        for(int i = 1; i < n; i++) {
            buy[i] = Math.max(buy[i-1], rest[i-1]-prices[i]);
            sell[i] = buy[i-1] + prices[i];
            rest[i] = Math.max(rest[i-1], sell[i-1]);
        }
        return Math.max(sell[n-1], rest[n-1]);
    }
}由于计算时只用到前一时刻的状态,因此无需使用数组,只需用一个变量记录前一时刻,space complexity为O(1)。
public class Solution {
    public int maxProfit(int[] prices) {
        if(prices == null || prices.length == 0) return 0;
        int sell = Integer.MIN_VALUE, buy = -prices[0], rest = 0;
        for(int i = 1; i < prices.length; i++) {
            int prevSell = sell;
            sell = buy + prices[i];
            buy = Math.max(buy, rest - prices[i]);
            rest = Math.max(rest, prevSell);
        }
        return Math.max(sell, rest);
    }
}