
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:
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股票的最大盈利。hold[0] = -prices[0]、
hold[1] = max(-prices[1], -prices[0])、
unhold[0] = 0。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:
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:
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
}