#309
Medium Algorithms Best time to buy and sell stock with cooldown
Array Dynamic Programming
61.7% acceptance
Jan 12, 2026
10024
348
You are given an array prices where prices[i] is the price of a given stock on the ith day.
Find the maximum profit you can achieve. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times) with the following restrictions:
After you sell your stock, you cannot buy stock on the next day (i.e., cooldown one day).
Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).
Solution
Rust
Time O(n)
Space O(1)
impl Solution {
pub fn max_profit_cooldown(prices: Vec<i32>) -> i32 {
if prices.len() <= 1 {
return 0;
}
let mut hold = -prices[0];
let mut sold = 0;
let mut rest = 0;
for i in 1..prices.len() {
let prev_hold = hold;
let prev_sold = sold;
let prev_rest = rest;
hold = prev_hold.max(prev_rest - prices[i]);
sold = prev_hold + prices[i];
rest = prev_rest.max(prev_sold);
}
sold.max(rest)
}
}