记忆化搜索,爆内存
class Solution:
def maxProfit(self, prices: List[int]):
n = len(prices)
@cache
def dfs(i, have, cnt, profit):
if cnt == 2:
return profit
if i == n:
return profit
# 当天买入
profit1 = 0
if have == 0 and cnt < 2:
profit1 = dfs(i + 1, 1, cnt, profit - prices[i])
# 当天卖出
profit2 = 0
if have == 1:
profit2 = dfs(i + 1, 0, cnt + 1, profit + prices[i])
# 当天不操作
profit3 = dfs(i + 1, have, cnt, profit)
return max(profit1, profit2, profit3)
return dfs(0, 0, 0, 0)
动态规划
class Solution {
public:
int maxProfit(vector<int>& prices) {
if (prices.size() == 0) return 0;
vector<int> dp(5, 0);
dp[1] = -prices[0];
dp[3] = -prices[0];
for (int i = 1; i < prices.size(); i++) {
dp[1] = max(dp[1], dp[0] - prices[i]);
dp[2] = max(dp[2], dp[1] + prices[i]);
dp[3] = max(dp[3], dp[2] - prices[i]);
dp[4] = max(dp[4], dp[3] + prices[i]);
}
return dp[4];
}
};
class Solution {
public:
int maxProfit(int k, vector<int>& prices) {
if (prices.size() == 0) return 0;
vector<vector<int>> dp(prices.size(), vector<int>(2 * k + 1, 0));
for (int j = 1; j < 2 * k; j += 2) {
dp[0][j] = -prices[0];
}
for (int i = 1; i < prices.size(); i++) {
for (int j = 0; j < 2 * k - 1; 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]);
}
}
return dp[prices.size() - 1][2 * k];
}
};