Skip to content

Commit 9a70d87

Browse files
authored
Create 04 - Space Optimized | DP | Approach.cpp
1 parent f09a030 commit 9a70d87

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
class Solution {
2+
public:
3+
// Helper function to calculate the maximum profit with transaction fee using dynamic programming (optimized space approach)
4+
int solve(vector<int>& prices, int fee) {
5+
int n = prices.size(); // Get the size of the prices array
6+
7+
// Initialize two arrays to store the maximum profit for the current and next states.
8+
// 'curr' will represent the current state (profit at index 'index'),
9+
// 'next' will represent the state for the next index (future state).
10+
vector<int> curr(2, 0);
11+
vector<int> next(2, 0);
12+
13+
// Iterate backwards through the prices array starting from the last index
14+
for(int index = n-1; index >= 0; index--) {
15+
// Iterate through both possible states: buy (1) or sell (0)
16+
for(int buy = 0; buy <= 1; buy++) {
17+
18+
int profit = 0;
19+
20+
// If we are in a "buy" state (buy == 1), we have two options:
21+
// 1. Buy the stock at the current price (represented by -prices[index]) and
22+
// move to the next index where we are in a "sell" state (next[0]).
23+
// 2. Do nothing and stay in the "buy" state at the next index (next[1]).
24+
if(buy) {
25+
int buyStock = -prices[index] + next[0]; // Buy stock
26+
int notBuyStock = 0 + next[1]; // Do nothing (stay in the "buy" state)
27+
profit = max(buyStock, notBuyStock); // Take the maximum of these two options
28+
} else {
29+
// If we are in a "sell" state (buy == 0), we have two options:
30+
// 1. Sell the stock at the current price and subtract the fee (represented by +prices[index] - fee)
31+
// and move to the next index where we are in a "buy" state (next[1]).
32+
// 2. Do nothing and stay in the "sell" state at the next index (next[0]).
33+
int sellStock = +prices[index] - fee + next[1]; // Sell stock and pay the fee
34+
int notSellStock = 0 + next[0]; // Do nothing (stay in the "sell" state)
35+
profit = max(sellStock, notSellStock); // Take the maximum of these two options
36+
}
37+
38+
// Store the calculated profit for the current state in the 'curr' array
39+
curr[buy] = profit;
40+
}
41+
42+
// Move the current state (curr) to the next state (next) for the next iteration
43+
next = curr;
44+
}
45+
46+
// Return the maximum profit starting from index 0 with the possibility of buying the stock (buy = 1)
47+
return next[1];
48+
}
49+
50+
// Main function to calculate the maximum profit with transaction fee
51+
int maxProfit(vector<int>& prices, int fee) {
52+
int n = prices.size(); // Get the size of the prices array
53+
return solve(prices, fee); // Call the solve function to calculate the maximum profit
54+
}
55+
};

0 commit comments

Comments
 (0)