[LeetCode]Best Time to Buy and Sell Stock with Cooldown

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:spa

  • You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).rest

  • After you sell your stock, you cannot buy stock on next day. (ie, cooldown 1 day)code

Example:ip

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

分析

由于当前日期买卖股票会受到以前日期买卖股票行为的影响,首先考虑到用DP解决。element

这道题比较麻烦的是有个cooldown的限制,其实本质也就是买与卖之间的限制。对于某一天,股票有三种状态: buy, sell, cooldown, sell与cooldown咱们能够合并成一种状态,由于手里最终都没股票,最终须要的结果是sell,即手里股票卖了得到最大利润。因此咱们能够用两个DP数组分别记录当前持股跟未持股的状态。而后根据题目中的限制条件,理清两个DP数组的表达式。it

对于当天最终未持股的状态,最终最大利润有两种可能,一是今天没动做跟昨天未持股状态同样,二是昨天持股了,今天卖了。因此咱们只要取这二者之间最大值便可,表达式以下:io

sellDp[i] = Math.max(sellDp[i - 1], buyDp[i - 1] + prices[i]);

对于当天最终持股的状态,最终最大利润有两种可能,一是今天没动做跟昨天持股状态同样,二是前天还没持股,今天买了股票,这里是由于cooldown的缘由,因此今天买股要追溯到前天的状态。咱们只要取这二者之间最大值便可,表达式以下:class

buyDp[i] = Math.max(buyDp[i - 1], sellDp[i - 2] - prices[i]);

最终咱们要求的结果是im

sellDp[n - 1] 表示最后一天结束时手里没股票时的累积最大利润

固然,这里空间复杂度是能够降到O(1)的,具体见第二种代码实现。

复杂度

time: O(n), space: O(n)

代码

public class Solution {
    public int maxProfit(int[] prices) {
        if (prices == null || prices.length == 0) {
            return 0;
        }
        
        // 表示当天最终未持股的状况下,当天结束后的累计最大利润
        int[] sellDp = new int[prices.length];
        // 表示当天最终持股的状况下,当天结束后的累计最大利润
        int[] buyDp = new int[prices.length];
        
        // 考虑初始状况
        buyDp[0] = -prices[0];
        sellDp[0] = 0;
        for (int i = 1; i < prices.length; i++) {
            sellDp[i] = Math.max(sellDp[i - 1], buyDp[i - 1] + prices[i]);
            if (i >= 2) {
                buyDp[i] = Math.max(buyDp[i - 1], sellDp[i - 2] - prices[i]);
            } else {
                buyDp[i] = Math.max(buyDp[i - 1], -prices[i]);
            }
        }
        return sellDp[prices.length - 1];
    }
}

代码(O(1) space)

public class Solution {
    public int maxProfit(int[] prices) {
        if (prices == null || prices.length == 0) {
            return 0;
        }
    
        int currBuy = -prices[0];
        int currSell = 0;
        int prevSell = 0;
        for (int i = 1; i < prices.length; i++) {
            int temp = currSell;
            currSell = Math.max(currSell, currBuy + prices[i]);
            if (i >= 2) {
                currBuy = Math.max(currBuy, prevSell - prices[i]);
            } else {
                currBuy = Math.max(currBuy, -prices[i]);
            }
            prevSell = temp;
        }
        return currSell;
    }
}
相关文章
相关标签/搜索