- 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:
Input: [1,2,3,0,2] Output: 3 Explanation: transactions = [buy, sell, cooldown, buy, sell]
视频讲解: https://www.bilibili.com/video/bv1bT4y1g76h
思路:
继续是买卖股票的变形题,这一题的多加了一个条件,就是卖完股票得要等一天(cooldown)才可以继续买股票。采用动态规划求解。
- 定义两个状态
hold[i]
和unhold[i]
分别表示第i天hold股票的最大盈利和不hold股票的最大盈利。 - 目标是unhold[n-1] (n为交易天数)
- base case
hold[0] = -prices[0]
、hold[1] = max(-prices[1], -prices[0])
、unhold[0] = 0
。 - 状态转移
hold[i]取最大值:
1、第i天买入
unhold[i-2] - prices[i]
2、第i天没有买入hold[i-1]
unhold[i]取最大值: 1、第i天卖出hold[i-1] prices[i]
2、第i天没有卖出unhold[i-1]
代码:
java:
代码语言:javascript复制class Solution {
public int maxProfit(int[] prices) {
if (prices == null || prices.length == 0) return 0;
int len = prices.length;
int[] hold = new int[len];
int[] unhold = new int[len];
hold[0] = -prices[0];
for (int i = 1; i < len; i ) {
if (i == 1) {
hold[i] = Math.max(hold[i-1], -prices[i]);
} else {
hold[i] = Math.max(hold[i-1], unhold[i-2] - prices[i]);
}
unhold[i] = Math.max(unhold[i-1], hold[i-1] prices[i]);
}
return unhold[len-1];
}
}
go:
代码语言:javascript复制func maxProfit(prices []int) int {
if prices == nil || len(prices) == 0 {
return 0
}
var hold = make([]int, len(prices))
var unhold = make([]int, len(prices))
hold[0] = -prices[0]
for i := 1; i < len(prices); i {
if i == 1 {
hold[i] = max(-prices[1], hold[0])
} else {
hold[i] = max(unhold[i-2] - prices[i], hold[i-1])
}
unhold[i] = max(hold[i-1] prices[i], unhold[i-1])
}
return unhold[len(prices) - 1]
}
func max(i, j int) int {
if i > j {
return i
}
return j
}