● 123.买卖股票的最佳时机III Best Time to Buy and Sell Stock III - LeetCode
dp[i][0] 不操作
dp[i][1] 第一次持有
dp[i][2] 第一次不持有
dp[i][3] 第二次持有
dp[i][4] 第二次不持有
dp[i][0] = dp[i - 1][0]
dp[i][1] = Max(dp[i - 1][1], dp[i-1][0] - prices[i])
dp[i][2] = max(dp[i - 1][2], dp[i - 1][1] + prices[i])
dp[i][3] = max(dp[i - 1][3], dp[i - 1][2] - prices[i])
dp[i][4] = max(dp[i - 1][4], dp[i - 1][3] + prices[i])
dp[0][0] = 0;
dp[0][1] = -prices[0]
dp[0][2] = 0;
dp[0][3] = -prices[0];
dp[0][4] = 0;
可以当天买卖
遍历顺序:从小到大
打印dp数组
一次过,震惊
class Solution {
public int maxProfit(int[] prices) {
int[][] dp = new int[prices.length][5];
//没有操作
dp[0][0] = 0;
//第一次买入
dp[0][1] = -prices[0];
//第一次卖出
dp[0][2] = 0;
//第二次买入
dp[0][3] = -prices[0];
//第二次卖出
dp[0][4] = 0;
for (int i = 1; i < prices.length; i++) {
dp[i][1] = Math.max(dp[i - 1][1], dp[i - 1][0] - prices[i]);
dp[i][2] = Math.max(dp[i - 1][2], dp[i - 1][1] + prices[i]);
dp[i][3] = Math.max(dp[i - 1][3], dp[i - 1][2] - prices[i]);
dp[i][4] = Math.max(dp[i - 1][4], dp[i - 1][3] + prices[i]);
}
return dp[prices.length - 1][4];
}
}
● 188.买卖股票的最佳时机IV Best Time to Buy and Sell Stock IV - LeetCode
dp[i][0] 不操作
dp[i][1]买入
dp[i][2] 卖出
j 一次跳跃两次
j + 1,买入
j + 2,卖出
for (j = 0; j < 2 * k; j += 2)
dp[i][j + 1] = max(dp[i - 1][j + 1], dp[i - 1][j] - prices[i]);
dp[i][j + 2] = max(dp[i - 1][j + 2], dp[i - 1][j + 1] + prices[i]);
class Solution {
public int maxProfit(int k, int[] prices) {
if (prices.length == 0) return 0;
int n = prices.length;
int[][] dp = new int[n][2 * k + 1];
for (int j = 1; j < 2 * k; j += 2) {
dp[0][j] = -prices[0];
}
for (int i = 1; i < n; i++) {
for (int j = 0; j < 2 * k - 1; j += 2) {
dp[i][j + 1] = Math.max(dp[i - 1][j + 1], dp[i - 1][j] - prices[i]);
dp[i][j + 2] = Math.max(dp[i - 1][j + 2], dp[i - 1][j + 1] + prices[i]);
}
}
return dp[n - 1][2 * k];
}
}