Hard
题目描述
给定一个数组 prices,其中 prices[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。
提示:
1 <= prices.length <= 10^50 <= prices[i] <= 10^5
解题思路
这是一道经典的动态规划题目,需要跟踪在最多两次交易下的最大利润。
解法一:四状态动态规划(推荐) 我们可以用四个变量来表示在每一天结束时的四种状态:
buy1:完成第一次买入操作后的最大利润(此时持有股票)sell1:完成第一次卖出操作后的最大利润buy2:完成第二次买入操作后的最大利润(此时持有股票)sell2:完成第二次卖出操作后的最大利润
状态转移方程:
buy1 = max(buy1, -prices[i]):要么保持之前的买入状态,要么今天买入sell1 = max(sell1, buy1 + prices[i]):要么保持之前的卖出状态,要么今天卖出buy2 = max(buy2, sell1 - prices[i]):基于第一次交易的利润进行第二次买入sell2 = max(sell2, buy2 + prices[i]):完成第二次卖出
解法二:通用K次交易 可以扩展为通用的最多K次交易问题,但对于K=2的情况,四状态解法更简洁高效。
时间复杂度O(n),空间复杂度O(1),这是最优解法。
代码实现
class Solution {
public:
int maxProfit(vector<int>& prices) {
int buy1 = -prices[0], sell1 = 0;
int buy2 = -prices[0], sell2 = 0;
for (int i = 1; i < prices.size(); i++) {
buy1 = max(buy1, -prices[i]);
sell1 = max(sell1, buy1 + prices[i]);
buy2 = max(buy2, sell1 - prices[i]);
sell2 = max(sell2, buy2 + prices[i]);
}
return sell2;
}
};
class Solution:
def maxProfit(self, prices: List[int]) -> int:
buy1 = -prices[0]
sell1 = 0
buy2 = -prices[0]
sell2 = 0
for i in range(1, len(prices)):
buy1 = max(buy1, -prices[i])
sell1 = max(sell1, buy1 + prices[i])
buy2 = max(buy2, sell1 - prices[i])
sell2 = max(sell2, buy2 + prices[i])
return sell2
public class Solution {
public int MaxProfit(int[] prices) {
int buy1 = -prices[0], sell1 = 0;
int buy2 = -prices[0], sell2 = 0;
for (int i = 1; i < prices.Length; i++) {
buy1 = Math.Max(buy1, -prices[i]);
sell1 = Math.Max(sell1, buy1 + prices[i]);
buy2 = Math.Max(buy2, sell1 - prices[i]);
sell2 = Math.Max(sell2, buy2 + prices[i]);
}
return sell2;
}
}
var maxProfit = function(prices) {
let buy1 = -prices[0], sell1 = 0;
let buy2 = -prices[0], sell2 = 0;
for (let i = 1; i < prices.length; i++) {
buy1 = Math.max(buy1, -prices[i]);
sell1 = Math.max(sell1, buy1 + prices[i]);
buy2 = Math.max(buy2, sell1 - prices[i]);
sell2 = Math.max(sell2, buy2 + prices[i]);
}
return sell2;
};
复杂度分析
| 复杂度类型 | 四状态DP解法 |
|---|---|
| 时间复杂度 | O(n) |
| 空间复杂度 | O(1) |
其中 n 是价格数组的长度。