Skip to content

Commit a5b3762

Browse files
authored
Create 08 - Number of Transaction | Space Optimization DP | Approach.cpp
1 parent 01e164e commit a5b3762

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
class Solution {
2+
public:
3+
// Function to calculate the maximum profit using space-optimized 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+
// `curr` and `next` arrays store the maximum profit for the current and next days
10+
// Each array has size `2*k+1`, representing all transaction states
11+
vector<int> curr(2 * k + 1, 0);
12+
vector<int> next(2 * k + 1, 0);
13+
14+
// Iterate through days in reverse order (bottom-up DP)
15+
for (int index = n - 1; index >= 0; index--) {
16+
// Iterate through all transaction states
17+
for (int transactionNo = 0; transactionNo < 2 * k; transactionNo++) {
18+
int profit = 0;
19+
20+
// Determine whether the current transaction is a "buy" or "sell"
21+
if (transactionNo % 2 == 0) { // Buy operation
22+
// Option 1: Buy the stock on the current day and move to the next transaction
23+
int buyStock = -prices[index] + next[transactionNo + 1];
24+
// Option 2: Skip buying and move to the next day
25+
int notBuyStock = 0 + next[transactionNo];
26+
// Maximize profit between buying and skipping
27+
profit = max(buyStock, notBuyStock);
28+
} else { // Sell operation
29+
// Option 1: Sell the stock on the current day and move to the next transaction
30+
int sellStock = +prices[index] + next[transactionNo + 1];
31+
// Option 2: Skip selling and move to the next day
32+
int notSellStock = 0 + next[transactionNo];
33+
// Maximize profit between selling and skipping
34+
profit = max(sellStock, notSellStock);
35+
}
36+
37+
// Store the calculated profit in the current day's array
38+
curr[transactionNo] = profit;
39+
}
40+
41+
// Move to the next day by updating `next` to `curr`
42+
next = curr;
43+
}
44+
45+
// The maximum profit starting from day 0 with no transactions made yet
46+
return next[0];
47+
}
48+
49+
// Main function to calculate the maximum profit with at most `k` transactions
50+
int maxProfit(int k, vector<int>& prices) {
51+
// Call the `solve` function to compute the maximum profit
52+
return solve(prices, k);
53+
}
54+
};

0 commit comments

Comments
 (0)