LeetCode309 best-time-to-buy-and-sell-stock-with-cooldown (最佳买卖股票的时机含冷冻期)

题目

You are given an array prices where prices[i] is the price of a given stock on the iᵗʰ day.

Find the maximum profit you can achieve. You may complete as many
transactions as you like (i.e., buy one and sell one share of the stock multiple times)
with the following restrictions:

After you sell your stock, you cannot buy stock on the next day (i.e., cooldown one day).

Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).

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

 Example 2: 
Input: prices = [1]
Output: 0

 Constraints: 
 1 <= prices.length <= 5000 
 0 <= prices[i] <= 1000 

方法

动态规划法

dp[i][0]:第i天结束手上有股票,可能是第i天买的,也可能是i-1之前买的
dp[i][1]:第i天结束手上无股票,第i天卖掉的
dp[i][2]:第i天结束手上无股票,第i天之前卖掉的,可能是i-1卖的也可能i-1之前卖的

  • 时间复杂度:O(n),n为数组长度
  • 空间复杂度:O(n)
class Solution {
    public int maxProfit(int[] prices) {
        int length = prices.length;
        if(length<=0){
            return 0;
        }
        int[][] dp = new int[length][3];
        dp[0][0] = -prices[0];
        for(int i=1;i<length;i++){
            dp[i][0] = Math.max(dp[i-1][0],dp[i-1][2]-prices[i]); //手中有股票
            dp[i][1] = dp[i-1][0]+prices[i];//手中无股票,i天之后有冷冻期
            dp[i][2] = Math.max(dp[i-1][1],dp[i-1][2]);//手中无股票,i天之后无冷冻期
        }
        return Math.max(dp[length-1][1],dp[length-1][2]);
    }
}

动态规划法-空间优化

  • 时间复杂度:O(n),n为数组长度
  • 空间复杂度:O(1)
class Solution {
    public int maxProfit(int[] prices) {
        int length = prices.length;
        int dp0 = -prices[0],dp1 = 0,dp2 = 0;
        for(int i=1;i<length;i++){
            int temp0 = dp0,temp1 = dp1;
            dp0 = Math.max(dp0,dp2-prices[i]);
            dp1 = temp0+prices[i];
            dp2 = Math.max(dp2,temp1);
        }
        return Math.max(dp1,dp2);
    }
}
posted @ 2021-10-26 15:39  你也要来一颗长颈鹿吗  阅读(28)  评论(0)    收藏  举报