题目:309. 买卖股票的最佳时机含冷冻期
思路:动态规划dp,时间复杂度为0(n)。细节看注释
C++版本:
class Solution {
public:
int maxProfit(vector<int>& prices) {
int n=prices.size();
vector<vector<int>> f(n+2,vector<int>(2,0));
// f[i][0]:指在第i-2天时,没有持有股票的情况下的最大值
// f[i][1]:指在第i-2天时,持有股票的情况下的最大值
// f[1][1]是一个非法状态,所以置为最小值
f[1][1]=INT_MIN;
for(int i=0;i<n;i++){
// f[i+2][0]:指在第i-2天时,没有持有股票的情况下的最大值
// f[i+2][0]的状态来源:1、f[i+1][0];2、f[i+1][1],且在第i-2天卖出
f[i+2][0]=max(f[i+1][0],f[i+1][1]+prices[i]);
// f[i+2][1]:指在第i-2天时,持有股票的情况下的最大值
// f[i+2][1]的状态来源:1、f[i+1][1];2、f[i][0],且在第i-2天买入股票。
// 为啥第二种来源,不考虑f[i+1][0]呢,是因为必须要隔一天,如果f[i+1][0]是已经隔了一天的情况,那其实就是等价于f[i][0]呀
f[i+2][1]=max(f[i+1][1],f[i][0]-prices[i]);
}
return f[n+1][0];
}
};
JAVA版本:
class Solution {
public int maxProfit(int[] prices) {
int n=prices.length;
int[][] f=new int[n+2][2];
f[1][1]=Integer.MIN_VALUE;
for(int i=0;i<n;i++){
f[i+2][0]=Math.max(f[i+1][0],f[i+1][1]+prices[i]);
f[i+2][1]=Math.max(f[i+1][1],f[i][0]-prices[i]);
}
return f[n+1][0];
}
}
Go版本:
func maxProfit(prices []int) int {
n:=len(prices)
f:=make([][]int,n+2)
for i:=range f {
f[i]=make([]int,2)
}
f[1][1]=-10000
for i:=0;i<n;i++ {
f[i+2][0]=max(f[i+1][0],f[i+1][1]+prices[i])
f[i+2][1]=max(f[i+1][1],f[i][0]-prices[i])
}
return f[n+1][0]
}