|
| 1 | +class Solution { |
| 2 | +public: |
| 3 | + int dp[50001][2]; |
| 4 | + int solve(vector<int> &prices, int fee, int own, int index) { |
| 5 | + |
| 6 | + //basecase |
| 7 | + if(index == prices.size()) |
| 8 | + return 0; |
| 9 | + |
| 10 | + if(dp[index][own] != -1) |
| 11 | + return dp[index][own]; |
| 12 | + |
| 13 | + if(own) { |
| 14 | + int case1 = prices[index] + solve(prices, fee, 0, index + 1); |
| 15 | + int case2 = solve(prices, fee, 1, index + 1); |
| 16 | + return dp[index][own] = max(case1, case2); |
| 17 | + } |
| 18 | + |
| 19 | + else { |
| 20 | + int case1 = -(fee + prices[index]) + solve(prices, fee, 1, index + 1); |
| 21 | + int case2 = solve(prices, fee, 0, index + 1); |
| 22 | + return dp[index][own] = max(case1, case2); |
| 23 | + } |
| 24 | + } |
| 25 | + |
| 26 | + int maxProfit(vector<int>& prices, int fee) { |
| 27 | + |
| 28 | + /* |
| 29 | + n = len(prices) |
| 30 | + if you own a stock at day `i`, you have two choices - |
| 31 | + - sell the stock at day `i + 1` and find the max profit incurred after day `i + 1` to `n` |
| 32 | + - do not sell the stock at day `i + 1` and find max profit incurred after day `i + 1` to `n` |
| 33 | + |
| 34 | + if you do not own a stock at day `i` you have two choices - |
| 35 | + - own a stock at day `i + 1` and find the max profit incurred after day `i + 1` to `n` |
| 36 | + - do not sell the stock at day `i + 1` and find max profit incurred after day `i + 1` to `n` |
| 37 | + */ |
| 38 | + memset(dp, -1, sizeof dp); |
| 39 | + return solve(prices, fee, 0, 0); |
| 40 | + } |
| 41 | +}; |
0 commit comments