1. Recursive Decision Tree with Cooldown Flag
Intuition
Recursively explore states solve(day, state) where state can be 0 (ready to buy), 1 (holding stock), or 2 (cooldown day).
Algorithm
- Define
dfs(day, state). - If
day == n, return 0. - If state == 1 (holding): choice 1 is sell
prices[day] + dfs(day + 1, 2); choice 2 is keepdfs(day + 1, 1). - If state == 2 (cooldown): must transition to rest
dfs(day + 1, 0). - If state == 0 (rest): choice 1 is buy
-prices[day] + dfs(day + 1, 1); choice 2 is skipdfs(day + 1, 0). - Return max of choices.
#include <iostream>#include <vector>#include <algorithm> using namespace std; int dfs(int day, int state, const vector<int>& prices) { if (day == (int)prices.size()) return 0; if (state == 1) { // holding int sell = prices[day] + dfs(day + 1, 2, prices); int keep = dfs(day + 1, 1, prices); return max(sell, keep); } else if (state == 2) { // cooldown return dfs(day + 1, 0, prices); } else { // rest / can buy int buy = -prices[day] + dfs(day + 1, 1, prices); int skip = dfs(day + 1, 0, prices); return max(buy, skip); }} int maxProfitRecursive(const vector<int>& prices) { return dfs(0, 0, prices);} int main() { vector<int> prices = {1, 2, 3, 0, 2}; cout << "Max Profit (Recursive): " << maxProfitRecursive(prices) << endl; return 0;}Time & Space Complexity
- Time complexity:
O(2^n) - Space complexity:
O(n) call stack