1. Recursive State Exploration
Intuition
At each day, decide whether to buy, sell (if holding), or do nothing. Recurse over all valid states.
Algorithm
- Define
solve(day, holding). - If
day == prices.length, return 0. - If holding: choice 1 is sell
prices[day] + solve(day + 1, false), choice 2 is holdsolve(day + 1, true). - If not holding: choice 1 is buy
-prices[day] + solve(day + 1, true), choice 2 is skipsolve(day + 1, false). - Return max of choices.
Recursive Decision Tree All Buy/Sell Schedules
2 of 2 questions left todayLowest initial purchase
Lowest initial purchase.
#include <iostream>#include <vector>#include <algorithm> using namespace std; int solveRec(int day, bool holding, const vector<int>& prices) { if (day == (int)prices.size()) return 0; if (holding) { int sell = prices[day] + solveRec(day + 1, false, prices); int keep = solveRec(day + 1, true, prices); return max(sell, keep); } else { int buy = -prices[day] + solveRec(day + 1, true, prices); int skip = solveRec(day + 1, false, prices); return max(buy, skip); }} int maxProfitRecursive(const vector<int>& prices) { return solveRec(0, false, prices);} int main() { vector<int> prices = {7, 1, 5, 3, 6, 4}; cout << "Max Profit (Recursive): " << maxProfitRecursive(prices) << endl; return 0;}Time & Space Complexity
- Time complexity:
O(2^n) - Space complexity:
O(n) recursion stack