Best Time to Buy and Sell Stock with Cooldown
You are given an array pricesprices[i]i-th
Example 1
Input: prices = [1, 2, 3, 0, 2]
Output: 3
Explanation: Buy on day 1 (price=1), sell on day 2 (price=2), cooldown on day 3, buy on day 4 (price=0), sell on day 5 (price=2). Profit = 3.
Output: 3
Explanation: Buy on day 1 (price=1), sell on day 2 (price=2), cooldown on day 3, buy on day 4 (price=0), sell on day 5 (price=2). Profit = 3.
Example 2
Input: prices = [1]
Output: 0
Output: 0
Solution Approach - State DP
We model three states: heldsoldrest
= max(previous held, previous rest - price): either keep holding or buy from rest state.held = previous held + price: sell the stock you were holding.sold = max(previous rest, previous sold): either stay resting or finish cooldown.rest- Answer is max(sold, rest) at the end.
Java
public class BestTimeBuySellStockWithCooldown {
public int maxProfit(int[] prices) {
int held = Integer.MIN_VALUE, sold = 0, rest = 0;
for (int price : prices) {
int prevHeld = held, prevSold = sold, prevRest = rest;
held = Math.max(prevHeld, prevRest - price);
sold = prevHeld + price;
rest = Math.max(prevRest, prevSold);
}
return Math.max(sold, rest);
}
}
Complexity Analysis:
Time complexity: O(n). Single pass through the array.
Space complexity: O(1). Three state variables.