Skip to content

309. Best Time to Buy and Sell Stock with Cooldown 👍

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
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;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
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;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
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