309. Best Time to Buy and Sell Stock with Cooldown
by Botao Xiao
309. Best Time to Buy and Sell Stock with Cooldown
Question
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]
Thinking:
- Method 1: dp
- 状态转移方程
- buy[i - 1]:当前一天不买入,sell[i - 2] - prices[i - 1]:两天前卖出时的最大收益-当天股票价格。
- buy[i] = Math.max(sell[i - 2] - prices[i - 1], buy[i - 1])
- sell[i - 1]:前一天的卖出最大值, buy[i - 1] + prices[i - 1]:买入的最大值加上当天股票的价格。
- sell[i] = Math.max(sell[i - 1], buy[i - 1] + prices[i - 1])
- 状态转移方程
class Solution {
public int maxProfit(int[] prices) {
if(prices == null || prices.length == 0) return 0;
int len = prices.length;
int[] buy = new int[len + 1];
int[] sell = new int[len + 1];
buy[1] = -prices[0];
for(int i = 2; i <= len; i++){
buy[i] = Math.max(sell[i - 2] - prices[i - 1], buy[i - 1]);
sell[i] = Math.max(sell[i - 1], buy[i - 1] + prices[i - 1]);
}
return sell[len];
}
}
Second time
class Solution {
public int maxProfit(int[] prices) {
if(prices == null || prices.length == 0) return 0;
int len = prices.length;
int[] s0 = new int[len + 1];
int[] s1 = new int[len + 1];
int[] s2 = new int[len + 1];
s1[1] = -prices[0];
for(int i = 2; i <= prices.length; i++){
s0[i] = Math.max(s0[i - 1], s2[i - 1]);
s1[i] = Math.max(s1[i - 1], s0[i - 1] - prices[i - 1]);
s2[i] = s1[i - 1] + prices[i - 1];
}
return Math.max(s0[len], s2[len]);
}
}
Reference
Subscribe via RSS