Skip to content

Commit a8e0da2

Browse files
authored
Create 02 - Top-Down | DP | Approach.cpp
1 parent 76918c9 commit a8e0da2

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
class Solution {
2+
public:
3+
// Helper function to calculate the maximum profit using dynamic programming
4+
int solve(vector<int>& prices, int index, int buy, int fee, vector<vector<int>>& dp) {
5+
int n = prices.size(); // Get the size of the prices array
6+
7+
// Base case: If we've reached the end of the array (index == n), no more transactions can be made
8+
if(index == n) return 0;
9+
10+
// If the result is already computed for this index and buy state, return it from dp array
11+
if(dp[index][buy] != -1) return dp[index][buy];
12+
13+
int profit = 0;
14+
15+
// If we are in a "buy" state (buy == 1), we can either:
16+
// 1. Buy the stock at current price (this is represented by -prices[index])
17+
// and move to the next index (index+1) in a "sell" state (buy = 0).
18+
// 2. Skip this index (do nothing) and stay in the "buy" state (buy = 1).
19+
if(buy) {
20+
profit = max((-prices[index] + solve(prices, index+1, 0, fee, dp)), // Buy and move to the sell state
21+
(0 + solve(prices, index+1, 1, fee, dp))); // Do nothing and stay in the buy state
22+
} else {
23+
// If we are in a "sell" state (buy == 0), we can either:
24+
// 1. Sell the stock at current price (this is represented by +prices[index] - fee)
25+
// and move to the next index (index+1) in a "buy" state (buy = 1).
26+
// 2. Skip this index (do nothing) and stay in the "sell" state (buy = 0).
27+
profit = max((+prices[index] - fee + solve(prices, index+1, 1, fee, dp)), // Sell and move to the buy state
28+
(0 + solve(prices, index+1, 0, fee, dp))); // Do nothing and stay in the sell state
29+
}
30+
31+
// Store the result in dp array and return it
32+
return dp[index][buy] = profit;
33+
}
34+
35+
// Main function to calculate the maximum profit with transaction fee
36+
int maxProfit(vector<int>& prices, int fee) {
37+
int n = prices.size(); // Get the size of the prices array
38+
39+
// Initialize the dp array with -1 (indicating no result is computed yet)
40+
// dp[i][0] represents the maximum profit we can have at index i without buying the stock
41+
// dp[i][1] represents the maximum profit we can have at index i while having the stock to sell
42+
vector<vector<int>> dp(n+1, vector<int>(2, -1));
43+
44+
// Start solving from index 0 with the possibility of buying (buy = 1)
45+
return solve(prices, 0, 1, fee, dp);
46+
}
47+
};

0 commit comments

Comments
 (0)