LeetCode 题解工作台
买卖股票的最佳时机 III
给定一个数组,它的第 i 个元素是一支给定的股票在第 i 天的价格。 设计一个算法来计算你所能获取的最大利润。你最多可以完成 两笔 交易。 注意: 你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。 示例 1: 输入: prices = [3,3,5,0,0,3,1,4] 输出: 6 解…
2
题型
7
代码语言
3
相关题
当前训练重点
困难 · 状态·转移·动态规划
答案摘要
我们定义以下几个变量,其中: - `f1` 表示第一次买入股票后的最大利润;
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 状态·转移·动态规划 题型思路
题目描述
给定一个数组,它的第 i 个元素是一支给定的股票在第 i 天的价格。
设计一个算法来计算你所能获取的最大利润。你最多可以完成 两笔 交易。
注意:你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。
示例 1:
输入:prices = [3,3,5,0,0,3,1,4] 输出:6 解释:在第 4 天(股票价格 = 0)的时候买入,在第 6 天(股票价格 = 3)的时候卖出,这笔交易所能获得利润 = 3-0 = 3 。 随后,在第 7 天(股票价格 = 1)的时候买入,在第 8 天 (股票价格 = 4)的时候卖出,这笔交易所能获得利润 = 4-1 = 3 。
示例 2:
输入:prices = [1,2,3,4,5] 输出:4 解释:在第 1 天(股票价格 = 1)的时候买入,在第 5 天 (股票价格 = 5)的时候卖出, 这笔交易所能获得利润 = 5-1 = 4 。 注意你不能在第 1 天和第 2 天接连购买股票,之后再将它们卖出。 因为这样属于同时参与了多笔交易,你必须在再次购买前出售掉之前的股票。
示例 3:
输入:prices = [7,6,4,3,1] 输出:0 解释:在这个情况下, 没有交易完成, 所以最大利润为 0。
示例 4:
输入:prices = [1] 输出:0
提示:
1 <= prices.length <= 1050 <= prices[i] <= 105
解题思路
方法一:动态规划
我们定义以下几个变量,其中:
f1表示第一次买入股票后的最大利润;f2表示第一次卖出股票后的最大利润;f3表示第二次买入股票后的最大利润;f4表示第二次卖出股票后的最大利润。
遍历过程中,直接使用 f1, f2, f3, f4 计算,考虑的是在同一天买入和卖出时,收益是 ,不会对答案产生影响。
最后返回 f4 即可。
时间复杂度 ,其中 为数组 prices 的长度。空间复杂度 。
class Solution:
def maxProfit(self, prices: List[int]) -> int:
# 第一次买入,第一次卖出,第二次买入,第二次卖出
f1, f2, f3, f4 = -prices[0], 0, -prices[0], 0
for price in prices[1:]:
f1 = max(f1, -price)
f2 = max(f2, f1 + price)
f3 = max(f3, f2 - price)
f4 = max(f4, f3 + price)
return f4
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(n) since each day updates a fixed number of states. Space complexity is O(1) because only four variables are maintained instead of storing all intermediate states. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Look for correct handling of up to two transactions without simultaneous holds.
- question_mark
Check if state transitions correctly track buy and sell decisions for both transactions.
- question_mark
Watch for off-by-one errors when updating profits across days.
常见陷阱
外企场景- error
Attempting to store profits for all transaction counts in an array can increase space unnecessarily.
- error
Overwriting states in the wrong order can cause incorrect profit calculations.
- error
Failing to consider zero transactions as a valid maximum profit scenario.
进阶变体
外企场景- arrow_right_alt
At most k transactions instead of two, requiring generalized DP with k states.
- arrow_right_alt
Allowing transaction fees, adjusting state updates to subtract fees when selling.
- arrow_right_alt
Restricting cooldown days between transactions, requiring extra states to track cooldown.