Skip to content

Commit 0035062

Browse files
authored
Create 04 - Space Optimized | DP | Approach.cpp
1 parent 4958f18 commit 0035062

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
class Solution {
2+
public:
3+
// Function to calculate the maximum profit using space-optimized dynamic programming
4+
int solve(vector<int>& prices) {
5+
int n = prices.size(); // Get the number of days
6+
7+
// Space-optimized DP approach:
8+
// Instead of a 2D table, use two 1D arrays to store current and next states
9+
vector<int> curr(2, 0); // Array to store the current day's profit for both states (buy/sell)
10+
vector<int> next(2, 0); // Array to store the next day's profit for both states (buy/sell)
11+
12+
// Iterate backward from the second last day to the first day
13+
for (int index = n - 1; index >= 0; index--) {
14+
// Iterate over the two states: buy (1) and sell (0)
15+
for (int buy = 0; buy <= 1; buy++) {
16+
int profit = 0; // Initialize profit for the current state
17+
18+
if (buy) {
19+
// If we are allowed to buy:
20+
// - Option 1: Buy the stock today (-prices[index]) and move to the next day with buy=0
21+
// - Option 2: Skip buying today and move to the next day with buy=1
22+
int buyStock = -prices[index] + next[0];
23+
int notBuyStock = 0 + next[1];
24+
profit = max(buyStock, notBuyStock);
25+
} else {
26+
// If we are allowed to sell:
27+
// - Option 1: Sell the stock today (+prices[index]) and move to the next day with buy=1
28+
// - Option 2: Skip selling today and move to the next day with buy=0
29+
int sellStock = +prices[index] + next[1];
30+
int notSellStock = 0 + next[0];
31+
profit = max(sellStock, notSellStock);
32+
}
33+
34+
// Store the profit for the current state in the current day's array
35+
curr[buy] = profit;
36+
}
37+
38+
// Update the next day's array with the current day's results
39+
next = curr;
40+
}
41+
42+
// The maximum profit starting from day 0 with the ability to buy (buy=1)
43+
return curr[1];
44+
}
45+
46+
// Main function to calculate the maximum profit
47+
int maxProfit(vector<int>& prices) {
48+
return solve(prices); // Call the solve function
49+
}
50+
};

0 commit comments

Comments
 (0)