买卖股票的最佳时机含冷冻期
309. 买卖股票的最佳时机含冷冻期 - 力扣(LeetCode)
public class Solution {
public int MaxProfit(int[] prices) {
if(prices.Length == 0)return 0;
int[,] dp= new int[prices.Length+1,4];
dp[0,0] = -prices[0];
for(int i=1;i<prices.Length;i++){
dp[i,0] = Math.Max(dp[i-1,0],Math.Max(dp[i - 1, 3] ,dp[i - 1, 1]) - prices[i]);
dp[i,1] = Math.Max(dp[i-1,1],dp[i-1,3]);
dp[i,2] = dp[i-1,0]+prices[i];
dp[i,3] = dp[i-1,2];
}
return Math.Max(dp[prices.Length-1,1],Math.Max(dp[prices.Length - 1, 3], dp[prices.Length - 1, 2]));
}
}
买卖股票的最佳时机含手续费
714. 买卖股票的最佳时机含手续费 - 力扣(LeetCode)
和122那题完全一样,就只要卖出时多减去手续费就行
public class Solution {
public int MaxProfit(int[] prices, int fee) {
if(prices.Length == 0)return 0;
int[,] dp = new int[prices.Length,2];
dp[0,0] = -prices[0];
for(int i=1;i<prices.Length;i++){
dp[i,0] = Math.Max(dp[i-1,0],dp[i-1,1]-prices[i]);
dp[i,1] = Math.Max(dp[i-1,1],dp[i-1,0]+prices[i]-fee);
}
return dp[prices.Length-1,1];
}
}