10. Stock Buy and Sell with Cooldown
β GFG solution to the Stock Buy and Sell with Cooldown problem: maximize profit from stock trading with mandatory cooldown period using dynamic programming state machine approach. π
The problem can be found at the following link: π Question Link
π§© Problem Description
You are given an array arr[] where the ith element represents the price of a stock on the ith day (all prices are non-negative integers). Your task is to find the maximum profit you can make by buying and selling stocks with the constraint that after selling a stock, you cannot buy again on the next day (i.e., there is a one-day cooldown).
You can perform multiple transactions (buy and sell multiple times), but you must sell the stock before buying again, and you must observe the cooldown period after each sale.
π Examples
Example 1
Input: arr[] = [0, 2, 1, 2, 3]
Output: 3
Explanation: You first buy on day 1, sell on day 2 then cool down, then buy on day 4, and sell on day 5.
The total profit earned is (2-0) + (3-2) = 3, which is the maximum achievable profit.Example 2
Input: arr[] = [3, 1, 6, 1, 2, 4]
Output: 7
Explanation: You first buy on day 2 and sell on day 3 then cool down, then again you buy on day 5
and then sell on day 6. Clearly, the total profit earned is (6-1) + (4-2) = 7, which is the maximum achievable profit.π Constraints
$1 \le \text{arr.size()} \le 10^5$
$1 \le \text{arr}[i] \le 10^4$
β
My Approach
The optimal approach uses Dynamic Programming with State Machine tracking three distinct states at each day:
State Machine DP with Constant Space
Define States:
buy: Maximum profit when we are ready to buy or holding a stock (can buy today).sell: Maximum profit when we just sold stock (cannot buy tomorrow).cooldown: Maximum profit when we are in cooldown period (can buy tomorrow).
State Transitions:
Buy State: Either continue holding previous buy state, or buy today using cooldown profit.
buy = max(previous_buy, cooldown - arr[i])
Sell State: Either continue with previous sell state, or sell today from buy state.
sell = max(previous_sell, previous_buy + arr[i])
Cooldown State: Take maximum of previous cooldown or previous sell (entering cooldown after selling).
cooldown = max(previous_cooldown, previous_sell)
Initialization:
Start with
buy = -arr[0](buying first stock).sell = 0andcooldown = 0(no profit initially).
Iterate Through Prices:
For each day, calculate new states based on previous states.
Store previous states temporarily to avoid overwriting during calculation.
Return Result:
Maximum of
sellandcooldownstates gives the maximum achievable profit.
π Time and Auxiliary Space Complexity
Expected Time Complexity: O(n), where n is the size of the array. We iterate through the array once, performing constant-time operations at each step to update the three states.
Expected Auxiliary Space Complexity: O(1), as we only use three integer variables (
buy,sell,cooldown) and their temporary copies, requiring constant additional space regardless of input size.
π§βπ» Code (C++)
class Solution {
public:
int maxProfit(vector<int>& arr) {
int n = arr.size();
if (n <= 1) return 0;
int buy = -arr[0], sell = 0, cooldown = 0;
for (int i = 1; i < n; i++) {
int prevBuy = buy, prevSell = sell;
buy = max(buy, cooldown - arr[i]);
sell = max(sell, prevBuy + arr[i]);
cooldown = max(cooldown, prevSell);
}
return max(sell, cooldown);
}
};β Code (Java)
class Solution {
public int maxProfit(int arr[]) {
int n = arr.length;
if (n <= 1) return 0;
int buy = -arr[0], sell = 0, cooldown = 0;
for (int i = 1; i < n; i++) {
int prevBuy = buy, prevSell = sell;
buy = Math.max(buy, cooldown - arr[i]);
sell = Math.max(sell, prevBuy + arr[i]);
cooldown = Math.max(cooldown, prevSell);
}
return Math.max(sell, cooldown);
}
}π Code (Python)
class Solution:
def maxProfit(self, arr):
n = len(arr)
if n <= 1: return 0
buy, sell, cooldown = -arr[0], 0, 0
for i in range(1, n):
prev_buy, prev_sell = buy, sell
buy = max(buy, cooldown - arr[i])
sell = max(sell, prev_buy + arr[i])
cooldown = max(cooldown, prev_sell)
return max(sell, cooldown)π§ Contribution and Support
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: π¬ Any Questions?. Let's make this learning journey more collaborative!
β If you find this helpful, please give this repository a star! β
πVisitor Count
Last updated