描述
Say you have an array for which the ith 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]
Credits:
Special thanks to @dietpepsi for adding this problem and creating all test cases.
題意梗概
這題還是股票系列的續集,不同的是加入了條件冷卻,在售出後的一天不能購買股票,需要隔一天才能購買股票,我沒想出太好的解決方案,參考了discussion裏的一些思路解答出此題。
思路
使用有限狀態機+DP思考
這題對於每一天有三種狀態:
- S0:手中未持有,可以購買
- S1:手中持有一股,可以出售
- S2:手中未持有,不能購買
狀態轉移情況如下:
對於那些可以由兩個以上狀態轉移得到的狀態,我們進行最優化選擇(可能就是DP
解答
class Solution {
public:
int maxProfit(vector<int>& prices) {
if (prices.size() <= 1) {
return 0;
}
int n = prices.size();
// no stock on hand, can buy
vector<int> s0(n, 0);
// one stock on hand, can sell
vector<int> s1(n, 0);
s1[0] = -prices[0];
// no stock on hand, need rest, can not buy
vector<int> s2(n, 0);
for (int i = 1; i < n; ++i) {
s0[i] = max(s0[i - 1], s2[i - 1]);
s1[i] = max(s1[i - 1], s0[i - 1] - prices[i]);
s2[i] = s1[i - 1] + prices[i];
}
return max(s0[n - 1], s2[n - 1]);
}
};