Skip to content

Commit 01e164e

Browse files
authored
Create 07 - Number of Transaction | Bottom-Up DP | Approach.cpp
1 parent 907ec77 commit 01e164e

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
class Solution {
2+
public:
3+
// Function to calculate the maximum profit using dynamic programming
4+
// `prices`: vector of stock prices
5+
// `k`: maximum number of transactions allowed
6+
int solve(vector<int>& prices, int k) {
7+
int n = prices.size(); // Number of days
8+
9+
// Create a DP table to store the maximum profit
10+
// `dp[i][j]`: Maximum profit achievable from day `i` onwards with transaction number `j`
11+
vector<vector<int>> dp(n + 1, vector<int>(2 * k + 1, 0));
12+
13+
// Iterate through days in reverse order (bottom-up DP)
14+
for (int index = n - 1; index >= 0; index--) {
15+
// Iterate through all possible transaction states
16+
for (int transactionNo = 0; transactionNo < 2 * k; transactionNo++) {
17+
int profit = 0;
18+
19+
// Determine whether the current transaction is a "buy" or "sell"
20+
if (transactionNo % 2 == 0) { // Buy operation
21+
// Option 1: Buy the stock on the current day and move to the next transaction
22+
int buyStock = -prices[index] + dp[index + 1][transactionNo + 1];
23+
// Option 2: Skip buying and move to the next day
24+
int notBuyStock = 0 + dp[index + 1][transactionNo];
25+
// Maximize profit between buying and skipping
26+
profit = max(buyStock, notBuyStock);
27+
} else { // Sell operation
28+
// Option 1: Sell the stock on the current day and move to the next transaction
29+
int sellStock = +prices[index] + dp[index + 1][transactionNo + 1];
30+
// Option 2: Skip selling and move to the next day
31+
int notSellStock = 0 + dp[index + 1][transactionNo];
32+
// Maximize profit between selling and skipping
33+
profit = max(sellStock, notSellStock);
34+
}
35+
36+
// Store the calculated profit in the DP table
37+
dp[index][transactionNo] = profit;
38+
}
39+
}
40+
41+
// The maximum profit starting from day 0 with no transactions made yet
42+
return dp[0][0];
43+
}
44+
45+
// Main function to calculate the maximum profit with at most `k` transactions
46+
int maxProfit(int k, vector<int>& prices) {
47+
int n = prices.size(); // Total number of days
48+
49+
// Call the solve function to compute the maximum profit
50+
return solve(prices, k);
51+
}
52+
};

0 commit comments

Comments
 (0)