309.最佳买卖股票时机含冷冻期
714.买卖股票的最佳时机含手续费
股票总结
语言:Java
链接:https://leetcode.cn/problems/best-time-to-buy-and-sell-stock-with-cooldown/
class Solution {
public int maxProfit(int[] prices) {
if(prices.length == 1) return 0;
//dp[i][j]
//0.买入状态
//1.两天前卖出状态
//2.今天卖出状态
//3.冷冻期(卖出后的一天)
//第i天进行股票的状态j
int[][] dp = new int[prices.length][4];
dp[0][0] = -prices[0];
//dp[0][2] = prices[0];
//股票一定是先买入才能卖出,所以除了状态0其余状态都初始化为0
for(int i = 1; i < prices.length; i++){
dp[i][0] = Math.max(dp[i - 1][0], Math.max(dp[i - 1][1], dp[i - 1][3]) - prices[i]);
dp[i][1] = Math.max(dp[i - 1][3], dp[i - 1][1]);
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][2], dp[prices.length - 1][3]));
}
}
链接:https://leetcode.cn/problems/best-time-to-buy-and-sell-stock-with-transaction-fee/
class Solution {
public int maxProfit(int[] prices, int fee) {
int[][] dp = new int[prices.length][2];
//第i天持有j只股票的最大收益
dp[0][1] = -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] - fee);
dp[i][1] = Math.max(dp[i - 1][1], dp[i - 1][0] - prices[i]);
}
return dp[prices.length - 1][0];
}
}
注意事项:股票问题中的状态并不是一种实时的结果,而是第i天所处的一种状态,理解“状态”的含义