Leetcode: 309. Best Time to Buy and Sell Stock with Cooldown 有冷却机制的炒股问题
问题描述
Say you have an array for which the i -th element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times) with the following restrictions:
- You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
- After you sell your stock, you cannot buy stock on next day. (ie, cooldown 1 day)
Example:
prices = [1, 2, 3, 0, 2]
maxProfit = 3
transactions = [buy, sell, cooldown, buy, sell]
可以无限次的买卖,但是必须卖了之后才能再买,而且卖了之后必须冷却一天(当天不能再买入)。
本题(传送门)是炒股问题 Best Time to Buy and Sell Stock(传送门)的一个变种,该系列还有II、III、IV。
解决方案
这里用有限状态自动机(Finite State Automaton),我们设计三种状态:
名称 | 状态类型 | 描述 |
---|---|---|
A | 起始状态,可终止 | 手上没有股票且可以买入 |
B | 非终止状态 | 持有股票,可以卖出也可以休息一天,不能买入 |
C | 可终止状态 | 刚刚卖掉股票之后的状态,不持有股票但还不能买 |
对于每一天,计算处于A/B/C状态下最高的利润分别是多少。返回最后一天A和C状态下利润的较大值。
class Solution {
public:
int maxProfit(vector<int>& prices) {
if (prices.empty()) return 0;
int n = prices.size();
if (n == 1) return 0;
vector<int> A(n, 0), B(n, 0), C(n, 0);
A[0] = 0;
B[0] = -prices[0];
C[0] = INT_MIN;
for (int i = 1; i<n; i++){
// A状态休息一天,或者C状态休息一天,则进入A状态
A[i] = max(A[i - 1], C[i - 1]);
// B状态休息一天,或者A状态买入股票,则进入B状态
B[i] = max(B[i - 1], A[i - 1] - prices[i]);
// B状态卖出股票后,进入C状态
C[i] = B[i - 1] + prices[i];
}
return max(A[n - 1], C[n - 1]);
}
};