188.买卖股票的最佳时机IV
本题是123.买卖股票的最佳时机III 的进阶版
视频讲解:动态规划来决定最佳时机,至多可以买卖K次!| LeetCode:188.买卖股票最佳时机4_哔哩哔哩_bilibili
class Solution {
public int maxProfit(int k, int[] prices) {
if (prices.length == 0) return 0;
int length = prices.length;
int[][][] profitMatrix = new int[length][k + 1][2];
for (int transaction = 0; transaction <= k; transaction++) {
profitMatrix[0][transaction][1] = -prices[0];
}
for (int day = 1; day < length; day++) {
for (int transaction = 1; transaction <= k; transaction++) {
profitMatrix[day][transaction][0] = Math.max(profitMatrix[day - 1][transaction][0], profitMatrix[day - 1][transaction][1] + prices[day]);
profitMatrix[day][transaction][1] = Math.max(profitMatrix[day - 1][transaction][1], profitMatrix[day - 1][transaction - 1][0] - prices[day]);
}
}
return profitMatrix[length - 1][k][0];
}
}
309.最佳买卖股票时机含冷冻期
本题加了一个冷冻期,状态就多了,有点难度,大家要把各个状态分清,思路才能清晰
视频讲解:动态规划来决定最佳时机,这次有冷冻期!| LeetCode:309.买卖股票的最佳时机含冷冻期_哔哩哔哩_bilibili
class Solution {
public int maxProfit(int[] prices) {
if (prices == null || prices.length < 2) {
return 0;
}
int[][] profitMatrix = new int[prices.length][2];
profitMatrix[0][0] = 0;
profitMatrix[0][1] = -prices[0];
profitMatrix[1][0] = Math.max(profitMatrix[0][0], profitMatrix[0][1] + prices[1]);
profitMatrix[1][1] = Math.max(profitMatrix[0][1], -prices[1]);
for (int day = 2; day < prices.length; day++) {
profitMatrix[day][0] = Math.max(profitMatrix[day - 1][0], profitMatrix[day - 1][1] + prices[day]);
profitMatrix[day][1] = Math.max(profitMatrix[day - 1][1], profitMatrix[day - 2][0] - prices[day]);
}
return profitMatrix[prices.length - 1][0];
}
}
714.买卖股票的最佳时机含手续费
相对122.买卖股票的最佳时机II ,本题只需要在计算卖出操作的时候减去手续费就可以了,代码几乎是一样的,可以尝试自己做一做。
视频讲解:动态规划来决定最佳时机,这次含手续费!| LeetCode:714.买卖股票的最佳时机含手续费_哔哩哔哩_bilibili
class Solution {
public int maxProfit(int[] prices, int fee) {
int[][] profitMatrix = new int[2][2];
int length = prices.length;
profitMatrix[0][0] = -prices[0];
for (int day = 1; day < length; day++) {
profitMatrix[day % 2][0] = Math.max(profitMatrix[(day - 1) % 2][0], profitMatrix[(day - 1) % 2][1] - prices[day]);
profitMatrix[day % 2][1] = Math.max(profitMatrix[(day - 1) % 2][1], profitMatrix[(day - 1) % 2][0] + prices[day] - fee);
}
return profitMatrix[(length - 1) % 2][1];
}
}
股票总结
股票问题做一个总结吧