0309. Best Time to Buy and Sell Stock with Cooldown
Description
**Input:** prices = [1,2,3,0,2]
**Output:** 3
**Explanation:** transactions = [buy, sell, cooldown, buy, sell]**Input:** prices = [1]
**Output:** 0ac
Last updated
**Input:** prices = [1,2,3,0,2]
**Output:** 3
**Explanation:** transactions = [buy, sell, cooldown, buy, sell]**Input:** prices = [1]
**Output:** 0Last updated
class Solution {
public int maxProfit(int[] prices) {
// edge cases
if (prices == null || prices.length <= 1) return 0;
int holdPrev = Integer.MIN_VALUE, emptyPrev = 0, cooldownPrev = 0;
for (int i = 0; i < prices.length; i++) {
int empty = Math.max(emptyPrev, cooldownPrev);
int hold = Math.max(holdPrev, emptyPrev-prices[i]);
int cooldown = holdPrev + prices[i];
holdPrev = hold;
emptyPrev = empty;
cooldownPrev = cooldown;
// make sure the variables are from last step, not updated in current step, hold, empty, cooldown
}
return Math.max(emptyPrev, cooldownPrev);
}
}