712198. Stock Buy and Sell – with Cooldown
Stock Buy and Sell – with Cooldown
Summary
The problem is to find the maximum profit that can be achieved by buying and selling a stock multiple times, with the constraint that after each buy or sell operation, you have to wait for one day before doing another. This problem involves dynamic programming and optimization.
Detailed Explanation
To solve this problem, we can use dynamic programming. We maintain an array dp where dp[i] represents the maximum profit we can get by the i-th day. Initially, dp[0] = 0, as we don't have any profit on the first day.
For each day i > 0, we calculate dp[i] in two ways:
- If we sell the stock on the current day, we add the maximum profit we can get by selling the stock up to the
(i-1)-thday (max(dp[j], -prices[j])) and subtract the price of the stock on that day. We then wait for one day before doing another operation. - If we don't sell the stock yet, we just add the maximum profit we can get by not selling the stock up to the
(i-1)-thday (dp[i-1]).
We take the maximum of these two options and update dp[i]. Finally, we return dp[n-1], where n is the number of days.
Here's a step-by-step breakdown:
dp[0] = 0
for i from 1 to n:
dp[i] = max(
// If we sell the stock on this day
prices[i-1] + dp[max(0, i-2)],
// If we don't sell the stock yet
dp[i-1]
)
return dp[n-1]
Time complexity: O(n), where n is the number of days.
Space complexity: O(n) for the dynamic programming array.
Optimized Solutions
Java
public int maxProfit(int[] prices) {
if (prices.length < 2) return 0;
int n = prices.length;
int[] dp = new int[n];
dp[0] = 0;
for (int i = 1; i < n; i++) {
dp[i] = Math.max(dp[i-1], prices[i-1] + (i > 1 ? dp[i-2] : 0));
}
return dp[n-1];
}