Skip to content

Commit 9c9b30a

Browse files
authored
Create 03 - Bottom-Up | DP | Approach.cpp
1 parent d97cff5 commit 9c9b30a

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
class Solution {
2+
public:
3+
// Iterative function to calculate the maximum profit using dynamic programming (bottom-up approach)
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(); // Total number of days
8+
9+
// Create a 3D DP table where:
10+
// dp[i][buy][limit]: Maximum profit achievable starting from day `i` with `buy` state and `limit` transactions left
11+
vector<vector<vector<int>>> dp(n + 1, vector<vector<int>>(2, vector<int>(k + 1, 0)));
12+
13+
// Iterate backwards over days (from the last day to the first day)
14+
for (int index = n - 1; index >= 0; index--) {
15+
// Iterate over the buy/sell state (0 = sell, 1 = buy)
16+
for (int buy = 0; buy <= 1; buy++) {
17+
// Iterate over the transaction limits (from 1 to k)
18+
for (int limit = 1; limit <= k; limit++) {
19+
int profit = 0; // Variable to store the profit for the current state
20+
21+
if (buy) {
22+
// If the current state allows buying, we have two options:
23+
// 1. Buy the stock at the current price, then move to the next day with `buy = 0`.
24+
// 2. Skip buying and move to the next day with `buy = 1`.
25+
int buyStock = -prices[index] + dp[index + 1][0][limit]; // Buying
26+
int notBuyStock = 0 + dp[index + 1][1][limit]; // Skipping
27+
profit = max(buyStock, notBuyStock); // Maximize profit
28+
} else {
29+
// If the current state allows selling, we have two options:
30+
// 1. Sell the stock at the current price, then move to the next day with `buy = 1` and decrement the transaction count.
31+
// 2. Skip selling and move to the next day with `buy = 0`.
32+
int sellStock = prices[index] + dp[index + 1][1][limit - 1]; // Selling
33+
int notSellStock = 0 + dp[index + 1][0][limit]; // Skipping
34+
profit = max(sellStock, notSellStock); // Maximize profit
35+
}
36+
37+
// Store the result in the DP table
38+
dp[index][buy][limit] = profit;
39+
}
40+
}
41+
}
42+
43+
// Return the maximum profit starting from day 0, with the ability to buy and `k` transactions available
44+
return dp[0][1][k];
45+
}
46+
47+
// Main function to calculate the maximum profit
48+
// `k`: maximum number of transactions allowed
49+
// `prices`: vector of stock prices
50+
int maxProfit(int k, vector<int>& prices) {
51+
int n = prices.size(); // Total number of days
52+
53+
// Call the solve function to compute the result using dynamic programming
54+
return solve(prices, k);
55+
}
56+
};

0 commit comments

Comments
 (0)