Best Time to Buy And Sell Stock With Cooldown: the idea to remember.
Maximize stock trading profit when each sale requires one cooldown day before buying again.
The core insight
Choose between skipping, buying, or selling; after a sale advance past the cooldown day.
Why it works
Day and holding state determine every legal future action, allowing repeated subproblems to share one best result.
The mistake to avoid
A sale advances two days before the next buy opportunity, while holding through a day advances one.
Commented Java solution
Use java.util.* imports and a surrounding solution class. Tree snippets assume the standard TreeNode definition; linked lists use ListNode and Clone Graph uses a Node with val and neighbors; Copy Random List uses Node with val, next and random. Read the input assumptions above.
// Java reference adapted from neetcode-gh/leetcode (MIT).
// Choose between skipping, buying, or selling; after a sale advance past the cooldown day.
public int maxProfit(int[] prices) {
Map<String, Integer> cache = new HashMap<>();
return dfs(prices, cache, 0, true);
}
public int dfs(
int[] prices,
Map<String, Integer> cache,
int index,
boolean buying
) {
if (index >= prices.length) {
return 0;
}
String key = index + "-" + buying;
if (cache.containsKey(key)) {
return cache.get(key);
}
int cooldown = dfs(prices, cache, index + 1, buying);
int buyOsell = Integer.MIN_VALUE;
if (buying) {
buyOsell = dfs(prices, cache, index + 1, !buying) - prices[index];
} else {
buyOsell = dfs(prices, cache, index + 2, !buying) + prices[index];
}
cache.put(key, Math.max(buyOsell, cooldown));
return cache.get(key);
}Java reference adapted from neetcode-gh/leetcode · MIT license
Make the next connection
Independent revision notes with credited Java references. Not affiliated with LeetCode or the source sheets.