1. Recursive Branching with Fee Penalty
Intuition
Branch at each day into buying, selling, or doing nothing, accounting for the fee whenever a transaction occurs.
Algorithm
- Define
dfs(day, holding). - If
day == prices.length, return 0. - If holding: choice 1 is sell
prices[day] - fee + dfs(day + 1, false); choice 2 is holddfs(day + 1, true). - If not holding: choice 1 is buy
-prices[day] + dfs(day + 1, true); choice 2 is skipdfs(day + 1, false). - Return max of choices.
Recursive Decision Tree with Fee Deduction
2 of 2 questions left todayRoot of decision tree
Root of decision tree.
#include <iostream>#include <vector>#include <algorithm> using namespace std; int dfsFee(int day, bool holding, int fee, const vector<int>& prices) { if (day == (int)prices.size()) return 0; if (holding) { int sell = prices[day] - fee + dfsFee(day + 1, false, fee, prices); int keep = dfsFee(day + 1, true, fee, prices); return max(sell, keep); } else { int buy = -prices[day] + dfsFee(day + 1, true, fee, prices); int skip = dfsFee(day + 1, false, fee, prices); return max(buy, skip); }} int maxProfitFeeRec(const vector<int>& prices, int fee) { return dfsFee(0, false, fee, prices);} int main() { vector<int> prices = {1, 3, 2, 8, 4, 9}; int fee = 2; cout << "Max Profit (Recursive): " << maxProfitFeeRec(prices, fee) << endl; return 0;}Time & Space Complexity
- Time complexity:
O(2^n) - Space complexity:
O(n) call stack