1. Recursive DFS with Memoization
Intuition
Explore recursive states (day, transactions_remaining, holding). At each step, either buy, sell, or skip.
Algorithm
- Define
dfs(day, k, holding). - Base Case: If
day == nork == 0, return 0. - If holding: choice 1 is sell
prices[day] + dfs(day + 1, k - 1, 0); choice 2 is keepdfs(day + 1, k, 1). - If not holding: choice 1 is buy
-prices[day] + dfs(day + 1, k, 1); choice 2 is skipdfs(day + 1, k, 0). - Return max of options.
Recursive Transaction Count Search
2 of 2 questions left todayFirst optimal trade
First optimal trade.
#include <iostream>#include <vector>#include <algorithm>#include <cstring> using namespace std; int memo[1005][105][2]; int dfs(int day, int k, int holding, const vector<int>& prices) { if (day == (int)prices.size() || k == 0) return 0; if (memo[day][k][holding] != -1) return memo[day][k][holding]; if (holding) { int sell = prices[day] + dfs(day + 1, k - 1, 0, prices); int keep = dfs(day + 1, k, 1, prices); return memo[day][k][holding] = max(sell, keep); } else { int buy = -prices[day] + dfs(day + 1, k, 1, prices); int skip = dfs(day + 1, k, 0, prices); return memo[day][k][holding] = max(buy, skip); }} int maxProfitMemo(int k, const vector<int>& prices) { if (prices.empty() || k == 0) return 0; memset(memo, -1, sizeof(memo)); return dfs(0, k, 0, prices);} int main() { vector<int> prices = {3, 2, 6, 5, 0, 3}; int k = 2; cout << "Max Profit (Memoized DFS): " << maxProfitMemo(k, prices) << endl; return 0;}Time & Space Complexity
- Time complexity:
O(2^n) without memo, O(n * k) with full 3D memo table - Space complexity:
O(n * k) memoization table and call stack