123. 买卖股票的最佳时机 III - 力扣(LeetCode)
class Solution {
public int maxProfit(int[] prices) {
int[] dp = new int[4];
//第一次买入
dp[0] = -prices[0];
//第一次卖出
dp[1] = 0;
//第二次买入
dp[2] = -prices[0];
//第二次卖出
dp[3] = 0;
for (int i = 1; i <= prices.length; i++) {
dp[0] = Math.max(dp[0], -prices[i - 1]);
dp[1] = Math.max(dp[1], dp[0] + prices[i - 1]);
dp[2] = Math.max(dp[2], dp[1] - prices[i - 1]);
dp[3] = Math.max(dp[3], dp[2] + prices[i - 1]);
}
return dp[3];
}
}
188. 买卖股票的最佳时机 IV - 力扣(LeetCode)
class Solution {
public int maxProfit(int k, int[] prices) {
if (prices.length == 0) return 0;
if (k == 0) return 0;
int[] dp = new int[k * 2];
for (int i = 0; i < dp.length / 2; i++) {
dp[i * 2] = -prices[0];
}
for (int i = 1; i <= prices.length; i++) {
dp[0] = Math.max(dp[0], -prices[i - 1]);
dp[1] = Math.max(dp[1], dp[0] + prices[i - 1]);
for (int j = 2; j < dp.length; j += 2) {
dp[j] = Math.max(dp[j], dp[j - 1] - prices[i - 1]);
dp[j + 1] = Math.max(dp[j + 1], dp[j] + prices[i - 1]);
}
}
return dp[dp.length - 1];
}
}