Skip to content

Commit 7b59fb0

Browse files
authored
Create 05 - Number of Transaction Recursive Approach (caused TLE).cpp
1 parent 5aa3c86 commit 7b59fb0

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
class Solution {
2+
public:
3+
// Recursive function to calculate the maximum profit
4+
// `prices`: vector of stock prices
5+
// `index`: current day index
6+
// `transactionNo`: current transaction number (0-based, where even = buy, odd = sell)
7+
// `k`: maximum number of transactions allowed
8+
int solve(vector<int>& prices, int index, int transactionNo, int k) {
9+
// Base case: if we reach the end of the prices array or have completed `2 * k` transactions
10+
if (index == prices.size() || transactionNo == 2 * k) return 0;
11+
12+
int profit = 0; // Variable to store the profit for the current state
13+
14+
// Check if the current transaction is a "buy" (even transactionNo)
15+
if (transactionNo % 2 == 0) {
16+
// Option 1: Buy the stock on the current day and move to the next transaction
17+
int buyStock = -prices[index] + solve(prices, index + 1, transactionNo + 1, k);
18+
// Option 2: Skip buying and move to the next day
19+
int notBuyStock = 0 + solve(prices, index + 1, transactionNo, k);
20+
// Maximize the profit between buying and skipping
21+
profit = max(buyStock, notBuyStock);
22+
} else {
23+
// If the current transaction is a "sell" (odd transactionNo)
24+
// Option 1: Sell the stock on the current day and move to the next transaction
25+
int sellStock = +prices[index] + solve(prices, index + 1, transactionNo + 1, k);
26+
// Option 2: Skip selling and move to the next day
27+
int notSellStock = 0 + solve(prices, index + 1, transactionNo, k);
28+
// Maximize the profit between selling and skipping
29+
profit = max(sellStock, notSellStock);
30+
}
31+
32+
return profit; // Return the profit for the current state
33+
}
34+
35+
// Function to calculate the maximum profit with at most `k` transactions
36+
// `k`: maximum number of transactions allowed
37+
// `prices`: vector of stock prices
38+
int maxProfit(int k, vector<int>& prices) {
39+
int n = prices.size(); // Total number of days
40+
41+
// Call the recursive function starting from day 0 and transaction number 0
42+
return solve(prices, 0, 0, k);
43+
}
44+
};

0 commit comments

Comments
 (0)