题目1
题解
又是股票系列的题,与之前的不同是,必须隔一天再买卖股票,不能前一天卖完第二天又买,其中隔的那一天叫冷冻期,所以冷冻期前一天肯定是卖股票了。
-
状态定义:
-
状态转移方程:
-
初始条件:dp[n-1][1]=dp[n-1][2]=0,dp[n-1][0]=-prices[0]
-
返回值:max(dp[n-1][1],dp[n-1][2])
class Solution {
public int maxProfit(int[] prices) {
int n=prices.length;
int dp[][]=new int[n][3];
dp[0][0]=-prices[0];//有股票
for(int i=1;i<n;i++){
dp[i][0]=Math.max(dp[i-1][0],dp[i-1][2]-prices[i]);
dp[i][1]=dp[i-1][0]+prices[i];//无股票,冷冻期
dp[i][2]=Math.max(dp[i-1][1],dp[i-1][2]);//无股票,非冷冻期
}
return Math.max(dp[n-1][1],dp[n-1][2]);
}
}
时间复杂度: O ( n ) O(n) O(n)
空间复杂度: O ( n ) O(n) O(n),亦可以使用滚动数组优化空间为O(1)
题目2
题解
就是买卖股票的最佳时机 II 多了一个手续费,代码几乎都一样
这回利用滚动数组优化了一下空间复杂度
class Solution {
public int maxProfit(int[] prices, int fee) {
int n=prices.length;
int hasStock=-prices[0];//有股票
int noHasStock=0;//没股票
for(int i=1;i<n;i++){
int tmp=noHasStock;
noHasStock=Math.max(noHasStock,hasStock+prices[i]-fee);
hasStock=Math.max(tmp-prices[i],hasStock);
}
return noHasStock;
}
}
时间复杂度: O ( n ) O(n) O(n)
空间复杂度: O ( 1 ) O(1) O(1)