309. Best Time to Buy and Sell Stock with Cooldown
Medium
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:
Input: [1,2,3,0,2]
Output: 3
Explanation: transactions = [buy, sell, cooldown, buy, sell]
题意
给定一个物品的价格序列,求通过不限次数地买卖该物品物品能够赚取的最大收入,限制卖出后会冻结操作一天。
思路
动态规划。
对于每一个交易日,有三种状态:休息Rest, 买入Buy, 卖出Sell,状态转移关系是:
prev action cur
Rest -> 休息 -> Rest
Rest -> 买入 -> Buy
Buy -> 休息 -> Buy
Buy -> 卖出 -> Sell
Sell -> 休息 -> Rest
3个动态规划数组rest/buy/sell分别表示当第i天的状态为休息/买入/卖出时的最大收益,根据三种状态的状态转移关系可以列出递推式:
rest[i] = max(rest[i-1], sell[i-1])
buy[i] = max(buy[i-1], rest[i-1] - prices[i])
sell[i] = buy[i-1] + prices[i]
代码
class Solution {
public int maxProfit(int[] prices) {
int n = prices.length;
if (n == 0) {
return 0;
}
int b0 = -prices[0], b1 = 0, s0 = 0, s1 = 0, r0 = 0, r1 = 0, i = 0;
for (i=1; i<n; ++i) {
b1 = Math.max(b0, r0 - prices[i]);
r1 = Math.max(r0, s0);
s1 = b0 + prices[i];
b0 = b1;
r0 = r1;
s0 = s1;
}
return Math.max(r1, s1);
}
}