You are given an array prices where prices[i] is the price of a given stock on the ith day.
Find the maximum profit you can achieve. You may complete at most two transactions.
Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).
Example 1:
Input: prices = [3,3,5,0,0,3,1,4]
Output: 6
Explanation: Buy on day 4 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3.
Then buy on day 7 (price = 1) and sell on day 8 (price = 4), profit = 4-1 = 3.
Example 2:
Input: prices = [1,2,3,4,5]
Output: 4
Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.
Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are engaging multiple transactions at the same time. You must sell before buying again.
Example 3:
Input: prices = [7,6,4,3,1]
Output: 0
Explanation: In this case, no transaction is done, i.e. max profit = 0.
Constraints:
1 <= prices.length <= 1050 <= prices[i] <= 105
122的加强版,限制了最多只能交易两次,就必须得用DP了,然而我现在啥也不会。
让gpt给的讲解,感觉还不错,虽然还是不能完全理解,但是可以死记硬背一下。
以下credit to GPT老师:
我们把整个交易过程拆成四个阶段:
状态 1:第一次买入
花钱买入,资金变少
状态 2:第一次卖出
完成第一笔交易,获得利润
状态 3:第二次买入
用之前赚到的钱,再次买入
状态 4:第二次卖出
完成第二笔交易,获得最终利润
我们分别用四个变量,记录每个阶段能达到的最大收益。
四个变量分别代表什么?
| 变量 | 含义 |
|---|---|
buy1 |
第一次买入后,能达到的最大资金余额 |
sell1 |
第一次卖出后,能达到的最大资金余额 |
buy2 |
第二次买入后,能达到的最大资金余额 |
sell2 |
第二次卖出后,能达到的最大资金余额 |
这里有一个关键的理解:
我们不是在记录某一天是否买卖,而是在记录截至当前,完成某个阶段所能达到的最优结果。
比如 buy1,假设我们可以选择在过去任意一天买入,那么买入价格越低,剩余资金就越多。因此:
buy1=max(buy1,-price)
为什么是 -price?因为我们把初始资金看作 0,买股票要花钱,所以买入后余额为负数。
同理,其他三个状态的更新公式是:
buy1 = max(buy1,-price)
sell1 = max(sell1,buy1+price)
buy2 = max(buy2,sell1-price)
sell2 = max(sell2,buy2+price)
直观理解:
-
buy1:之前已经买过,还是今天买更划算? -
sell1:之前已经卖过,还是今天卖更划算? -
buy2:之前已经开始第二次买入,还是用当前价格买更划算? -
sell2:之前已经完成第二次卖出,还是今天卖更划算?
每一天都更新这四个状态,最终的 sell2 就是最多两次交易的最大利润。
class Solution {
public int maxProfit(int[] prices) {
int buy1 = Integer.MIN_VALUE;
int sell1 = 0;
int buy2 = Integer.MIN_VALUE;
int sell2 = 0;
for (int price : prices) {
buy1 = Math.max(buy1, -price);
sell1 = Math.max(sell1, buy1 + price);
buy2 = Math.max(buy2, sell1 - price);
sell2 = Math.max(sell2, buy2 + price);
}
return sell2;
}
}