题目
给定一个数组,它的第 i 个元素是一支给定的股票在第 i 天的价格。
设计一个算法来计算你所能获取的最大利润。你最多可以完成 两笔 交易。
注意:你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。
- 来源:力扣(LeetCode)
- 链接:leetcode-cn.com/problems/be…
- 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路
每一天可能有5种状态:
- 什么也不操作
- 第一次交易买入
- 第一次交易卖出,完成了第一笔交易
- 第二次交易买入
- 第二次交易卖出 第i天的操作,可以由前一天的这4种状态转移而成。
- buy1(i) = Math.max(不买入buy1(i-1) , 买入-price[i])
- sell1(i) = Math.max(不卖sell1(i-1) , 卖掉(是在buy1(i)的基础上卖出) buy1(i) + price[i])
- buy2(i) = Math.max(不买入buy2(i-1), 买入(这次是在上次卖出的基础上买入的)sell1(i)-price[i])
- sell2(i) = Math.max(不卖 sell2(i-1), 卖掉 buy2(i) + price[i])
代码
public static int maxProfit(int[] prices) {
int buy1 = -prices[0];
int sell1 = 0;
int buy2 = -prices[0];
int 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;
}
复杂度
时间复杂度:O(n) 空间复杂度:O(1)