LeetCode 题解工作台

买卖股票的最佳时机含冷冻期

给定一个整数数组 prices ,其中第 prices[i] 表示第 i 天的股票价格 。​ 设计一个算法计算出最大利润。在满足以下约束条件下,你可以尽可能地完成更多的交易(多次买卖一支股票): 卖出股票后,你无法在第二天买入股票 (即冷冻期为 1 天)。 注意: 你不能同时参与多笔交易(你必须在再…

category

2

题型

code_blocks

5

代码语言

hub

3

相关题

当前训练重点

中等 · 状态·转移·动态规划

bolt

答案摘要

我们设计一个函数 $dfs(i, j)$,表示从第 天开始,状态为 时,能够获得的最大利润。其中 的取值为 $0, 1$,分别表示当前不持有股票和持有股票。答案即为 $dfs(0, 0)$。 函数 $dfs(i, j)$ 的执行逻辑如下:

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 状态·转移·动态规划 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给定一个整数数组prices,其中第  prices[i] 表示第 i 天的股票价格 。​

设计一个算法计算出最大利润。在满足以下约束条件下,你可以尽可能地完成更多的交易(多次买卖一支股票):

  • 卖出股票后,你无法在第二天买入股票 (即冷冻期为 1 天)。

注意:你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。

 

示例 1:

输入: prices = [1,2,3,0,2]
输出: 3 
解释: 对应的交易状态为: [买入, 卖出, 冷冻期, 买入, 卖出]

示例 2:

输入: prices = [1]
输出: 0

 

提示:

  • 1 <= prices.length <= 5000
  • 0 <= prices[i] <= 1000
lightbulb

解题思路

方法一:记忆化搜索

我们设计一个函数 dfs(i,j)dfs(i, j),表示从第 ii 天开始,状态为 jj 时,能够获得的最大利润。其中 jj 的取值为 0,10, 1,分别表示当前不持有股票和持有股票。答案即为 dfs(0,0)dfs(0, 0)

函数 dfs(i,j)dfs(i, j) 的执行逻辑如下:

如果 ini \geq n,表示已经没有股票可以交易了,此时返回 00

否则,我们可以选择不交易,此时 dfs(i,j)=dfs(i+1,j)dfs(i, j) = dfs(i + 1, j)。我们也可以进行股票交易,如果此时 j>0j \gt 0,说明当前持有股票,可以卖出,此时 dfs(i,j)=prices[i]+dfs(i+2,0)dfs(i, j) = prices[i] + dfs(i + 2, 0);如果此时 j=0j = 0,说明当前不持有股票,可以买入,此时 dfs(i,j)=prices[i]+dfs(i+1,1)dfs(i, j) = -prices[i] + dfs(i + 1, 1)。取最大值作为函数 dfs(i,j)dfs(i, j) 的返回值。

答案为 dfs(0,0)dfs(0, 0)

为了避免重复计算,我们使用记忆化搜索的方法,用一个数组 ff 记录 dfs(i,j)dfs(i, j) 的返回值,如果 f[i][j]f[i][j] 不为 1-1,说明已经计算过,直接返回 f[i][j]f[i][j] 即可。

时间复杂度 O(n)O(n),空间复杂度 O(n)O(n)。其中 nn 为数组 pricesprices 的长度。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        @cache
        def dfs(i: int, j: int) -> int:
            if i >= len(prices):
                return 0
            ans = dfs(i + 1, j)
            if j:
                ans = max(ans, prices[i] + dfs(i + 2, 0))
            else:
                ans = max(ans, -prices[i] + dfs(i + 1, 1))
            return ans

        return dfs(0, 0)
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Candidate correctly identifies the need for dynamic programming.

  • question_mark

    Candidate uses a space-optimized solution.

  • question_mark

    Candidate understands state transition and cooldown mechanics.

warning

常见陷阱

外企场景
  • error

    Forgetting to handle the cooldown after selling the stock.

  • error

    Incorrectly calculating profit by not tracking the maximum at each state transition.

  • error

    Using O(n) space when O(1) space is possible.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Modifying the problem to include transaction limits.

  • arrow_right_alt

    Allowing only one transaction (single buy and sell).

  • arrow_right_alt

    Adding more complicated cooldown conditions, such as cooldown lengths longer than one day.

help

常见问题

外企场景

买卖股票的最佳时机含冷冻期题解:状态·转移·动态规划 | LeetCode #309 中等