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 @   你也要来一颗长颈鹿吗  阅读(25)  评论(0编辑  收藏  举报
编辑推荐:
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
阅读排行:
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
点击右上角即可分享
微信分享提示