309.最佳买卖股票时机含冷冻期
- 刷题https://leetcode.cn/problems/best-time-to-buy-and-sell-stock-with-cooldown/description/
- 文章讲解https://programmercarl.com/0309.%E6%9C%80%E4%BD%B3%E4%B9%B0%E5%8D%96%E8%82%A1%E7%A5%A8%E6%97%B6%E6%9C%BA%E5%90%AB%E5%86%B7%E5%86%BB%E6%9C%9F.html
- 视频讲解https://www.bilibili.com/video/BV1rP4y1D7ku/?vd_source=af4853e80f89e28094a5fe1e220d9062
-
题解:
class Solution {
public int maxProfit(int[] prices) {
if (prices == null || prices.length < 2) {
return 0;
}
int[][] dp = new int[prices.length][2];
// bad case
dp[0][0] = 0;
dp[0][1] = -prices[0];
dp[1][0] = Math.max(dp[0][0], dp[0][1] + prices[1]);
dp[1][1] = Math.max(dp[0][1], -prices[1]);
for (int i = 2; i < prices.length; i++) {
// dp公式
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 - 2][0] - prices[i]);
}
return dp[prices.length - 1][0];
}
}
714.买卖股票的最佳时机含手续费
- 刷题https://leetcode.cn/problems/best-time-to-buy-and-sell-stock-with-transaction-fee/description/
- 文章讲解https://programmercarl.com/0714.%E4%B9%B0%E5%8D%96%E8%82%A1%E7%A5%A8%E7%9A%84%E6%9C%80%E4%BD%B3%E6%97%B6%E6%9C%BA%E5%90%AB%E6%89%8B%E7%BB%AD%E8%B4%B9%EF%BC%88%E5%8A%A8%E6%80%81%E8%A7%84%E5%88%92%EF%BC%89.html
- 视频讲解https://www.bilibili.com/video/BV1z44y1Z7UR/?vd_source=af4853e80f89e28094a5fe1e220d9062
-
题解:
class Solution {
public int maxProfit(int[] prices, int fee) {
int f0 = 0, f1 = -prices[0];
for (int i = 1; i < prices.length; ++i) {
int g0 = Math.max(f0, f1 + prices[i] - fee);
f1 = Math.max(f1, f0 - prices[i]);
f0 = g0;
}
return f0;
}
}