LeetCode Solutions
309. Best Time to Buy and Sell Stock with Cooldown
Time: $O(n)$ Space: $O(1)$
class Solution {
public:
int maxProfit(vector<int>& prices) {
int sell = 0;
int hold = INT_MIN;
int prev = 0;
for (const int price : prices) {
const int cache = sell;
sell = max(sell, hold + price);
hold = max(hold, prev - price);
prev = cache;
}
return sell;
}
};
class Solution {
public int maxProfit(int[] prices) {
int sell = 0;
int hold = Integer.MIN_VALUE;
int prev = 0;
for (final int price : prices) {
final int cache = sell;
sell = Math.max(sell, hold + price);
hold = Math.max(hold, prev - price);
prev = cache;
}
return sell;
}
}
class Solution:
def maxProfit(self, prices: List[int]) -> int:
sell = 0
hold = -math.inf
prev = 0
for price in prices:
cache = sell
sell = max(sell, hold + price)
hold = max(hold, prev - price)
prev = cache
return sell