309. 最佳买卖股票时机含冷冻期
class Solution {
public int maxProfit(int[] prices) {
int length = prices.length;
int[] dp = new int[4];
dp[0] = -prices[0];
for(int i = 0;i < length;i++){
int temp1 = dp[0];
int temp2 = dp[2];
//买入状态:一直持有股票,前一天不持有当天买入(加上之前卖出的利润),前一天是冰冻期时当天买入
dp[0] = Math.max(dp[0],Math.max(dp[1] - prices[i],dp[3] - prices[i]));
//卖出状态中的一直不持有:前一天也不持有,前一天是冷冻期
dp[1] = Math.max(dp[1],dp[3]);
//卖出状态中的当天卖出(前面肯定没有冷冻期并且一定持有股票才会卖):之前买入现在卖出
dp[2] = temp1 + prices[i];
//冷冻期(前一天肯定卖了才会有冷冻期),前一天的当天卖出
dp[3] = temp2;
}
return Math.max(dp[1],Math.max(dp[2],dp[3]));
}
}
714. 买卖股票的最佳时机含手续费
贪心算法:
不太好想,买入的时候加上手续费
class Solution {
public int maxProfit(int[] prices, int fee) {
int buy = prices[0] + fee;
int sum = 0;
for(int price:prices){
if(price > buy){
sum += price - buy;
buy = price;
}else if(price + fee < buy){
buy = price + fee;
}
}
return sum;
}
}
比较好理解就是卖出时候减去手续费即可
class Solution {
public int maxProfit(int[] prices, int fee) {
int[] dp = new int[2];
dp[0] = -prices[0];
for(int i = 0;i < prices.length;i++){
dp[0] = Math.max(dp[0],dp[1] - prices[i]);
dp[1] = Math.max(dp[1],dp[0] + prices[i] - fee);
}
return dp[1];
}
}