Skip to content

Commit 76918c9

Browse files
authored
Create 01 - Recursive Approach (caused TLE).cpp
1 parent c2356ca commit 76918c9

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
class Solution {
2+
public:
3+
// Helper function to calculate the maximum profit
4+
int solve(vector<int>& prices, int index, int buy, int fee) {
5+
int n = prices.size(); // Get the size of the prices array
6+
7+
// Base case: If we've reached the end of the array, no more transactions can be made
8+
if(index == n) return 0;
9+
10+
int profit = 0;
11+
12+
// If we are in a buying state (buy == 1), we can either:
13+
// 1. Buy the stock at current price (this is represented by -prices[index])
14+
// and move to the next index (index+1) in a "sell" state (buy = 0).
15+
// 2. Skip this index (do nothing) and stay in the "buy" state (buy = 1).
16+
if(buy) {
17+
profit = max((-prices[index] + solve(prices, index+1, 0, fee)), // Buy and move to the sell state
18+
(0 + solve(prices, index+1, 1, fee))); // Do nothing and stay in the buy state
19+
} else {
20+
// If we are in a selling state (buy == 0), we can either:
21+
// 1. Sell the stock at current price (this is represented by +prices[index] - fee)
22+
// and move to the next index (index+1) in a "buy" state (buy = 1).
23+
// 2. Skip this index (do nothing) and stay in the "sell" state (buy = 0).
24+
profit = max((+prices[index] - fee + solve(prices, index+1, 1, fee)), // Sell and move to the buy state
25+
(0 + solve(prices, index+1, 0, fee))); // Do nothing and stay in the sell state
26+
}
27+
28+
// Return the maximum profit for the current state
29+
return profit;
30+
}
31+
32+
// Main function to calculate the maximum profit with transaction fee
33+
int maxProfit(vector<int>& prices, int fee) {
34+
// Start solving from index 0 with the possibility of buying (buy = 1)
35+
return solve(prices, 0, 1, fee);
36+
}
37+
};

0 commit comments

Comments
 (0)