Skip to content

Commit b6dcaba

Browse files
authored
Create 01 - Recursive Approach (caused TLE).cpp
1 parent 8d57a40 commit b6dcaba

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
class Solution {
2+
public:
3+
// Recursive helper function to calculate the maximum profit
4+
// `prices`: vector of stock prices
5+
// `index`: current day index in the prices array
6+
// `buy`: indicates whether we are allowed to buy (1) or need to sell (0)
7+
// `k`: remaining transactions we are allowed to perform
8+
int solve(vector<int>& prices, int index, int buy, int k) {
9+
int n = prices.size(); // Number of days in the prices array
10+
11+
// Base case: if we've reached the end of the array or have no transactions left, return 0
12+
if(index == n || k == 0) return 0;
13+
14+
int profit = 0; // Variable to store the maximum profit at the current state
15+
16+
if(buy) {
17+
// If we are allowed to buy, we have two choices:
18+
// 1. Buy the stock on this day and subtract its price from profit, then move to the next day with `buy = 0`.
19+
// 2. Skip buying and move to the next day with `buy = 1`.
20+
profit = max(
21+
-prices[index] + solve(prices, index + 1, 0, k), // Buy
22+
0 + solve(prices, index + 1, 1, k) // Skip
23+
);
24+
} else {
25+
// If we are not allowed to buy (we need to sell), we have two choices:
26+
// 1. Sell the stock on this day and add its price to profit, then move to the next day with `buy = 1` and decrement transactions.
27+
// 2. Skip selling and move to the next day with `buy = 0`.
28+
profit = max(
29+
prices[index] + solve(prices, index + 1, 1, k - 1), // Sell
30+
0 + solve(prices, index + 1, 0, k) // Skip
31+
);
32+
}
33+
34+
return profit; // Return the maximum profit for this state
35+
}
36+
37+
// Main function to calculate the maximum profit
38+
// `k`: maximum number of transactions allowed
39+
// `prices`: vector of stock prices
40+
int maxProfit(int k, vector<int>& prices) {
41+
// Start the recursive process from day 0, with the ability to buy and `k` transactions remaining
42+
return solve(prices, 0, 1, k);
43+
}
44+
};

0 commit comments

Comments
 (0)