Skip to content

Commit 9b7558e

Browse files
authored
Create 02 - Top-Down | DP | Approach.cpp
1 parent 4eabf5c commit 9b7558e

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
class Solution {
2+
public:
3+
// Helper function to calculate the maximum profit using recursion and memoization
4+
// Parameters:
5+
// prices - reference to the price array
6+
// index - current day we are processing
7+
// buy - whether we are allowed to buy (1) or sell (0) on the current day
8+
// dp - 2D vector for memoization to store intermediate results
9+
int solve(vector<int>& prices, int index, int buy, vector<vector<int>>& dp) {
10+
// Base case: If we have processed all the days, there is no profit to be made
11+
if (index == prices.size()) return 0;
12+
13+
// If the result for this state is already computed, return it
14+
if (dp[index][buy] != -1) return dp[index][buy];
15+
16+
int profit = 0; // Initialize profit for the current state
17+
18+
if (buy) {
19+
// If we are allowed to buy on this day, we have two choices:
20+
// 1. Buy the stock today: Subtract prices[index] and move to the next day with buy=0 (since we now own the stock).
21+
// 2. Skip buying today: Move to the next day and keep buy=1.
22+
profit = max(
23+
(-prices[index] + solve(prices, index + 1, 0, dp)), // Option 1: Buy today
24+
(0 + solve(prices, index + 1, 1, dp)) // Option 2: Skip buying
25+
);
26+
} else {
27+
// If we are allowed to sell on this day, we have two choices:
28+
// 1. Sell the stock today: Add prices[index] to profit and move to the next day with buy=1 (since we no longer own the stock).
29+
// 2. Skip selling today: Move to the next day and keep buy=0.
30+
profit = max(
31+
(+prices[index] + solve(prices, index + 1, 1, dp)), // Option 1: Sell today
32+
(0 + solve(prices, index + 1, 0, dp)) // Option 2: Skip selling
33+
);
34+
}
35+
36+
// Store the computed profit for the current state in the dp table
37+
return dp[index][buy] = profit;
38+
}
39+
40+
// Main function to calculate the maximum profit
41+
int maxProfit(vector<int>& prices) {
42+
int n = prices.size(); // Get the number of days
43+
44+
// Create a 2D dp table with dimensions (n+1) x 2
45+
// dp[i][buy] stores the maximum profit from day i onward with the ability to buy or sell
46+
vector<vector<int>> dp(n + 1, vector<int>(2, -1));
47+
48+
// Start from the first day (index=0) with the ability to buy (buy=1)
49+
return solve(prices, 0, 1, dp);
50+
}
51+
};

0 commit comments

Comments
 (0)