309. Best Time to Buy and Sell Stock with Cooldown
Asked at 9Apple40Google32Bloomberg25Amazon18Microsoft12Infosys30Geico88AQR Capital Management66TikTok35
Problem
prices[i] is a stock's price on day i. Make as many buy-then-sell transactions as you like, holding at most one share at a time, but after selling you can't buy on the next day (one-day cooldown). Return the maximum profit.
Example: [1,2,3,0,2] → 3 (buy, sell, cooldown, buy, sell)
Three states per day: hold (own a share), sold (just sold today → cooldown tomorrow), rest (free, not holding).
buy sell
rest ---------> hold ------------> sold
^ \__/ \__/ |
| stay stay |
+---------- cooldown --------------+
Complexity: O(n) time, O(1) space.
class Solution:
def maxProfit(self, prices: List[int]) -> int:
hold, sold, rest = float("-inf"), 0, 0
for p in prices:
hold, sold, rest = max(hold, rest - p), hold + p, max(rest, sold)
return max(sold, rest)
assert Solution().maxProfit([1, 2, 3, 0, 2]) == 3
assert Solution().maxProfit([1]) == 0
class Solution {
public int maxProfit(int[] prices) {
int hold = Integer.MIN_VALUE / 2, sold = 0, rest = 0;
for (int p : prices) {
int h = Math.max(hold, rest - p), s = hold + p, r = Math.max(rest, sold);
hold = h; sold = s; rest = r;
}
return Math.max(sold, rest);
}
}
func maxProfit(prices []int) int {
hold, sold, rest := math.MinInt/2, 0, 0 // holding a share / just sold / free to buy
for _, p := range prices {
hold, sold, rest = max(hold, rest-p), hold+p, max(rest, sold)
}
return max(sold, rest)
}