Best Time to Buy and Sell Stock with Cooldown

MediumDynamic Programming1d dp

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

prices[i] is the price of a stock on day i. You may complete as many buy/sell transactions as you like, subject to two rules: - You hold at most one share at a time, so you must sell before buying again. - The day after any sale is a cooldown day on which you may not buy. Return the maximum total profit you can make. If no trade is profitable, return 0.

Examples

Input: prices = [1,2,3,0,2]
Output: 3
Buy at 1, sell at 2, cool down, buy at 0, sell at 2: profit 1 + 2 = 3.
Input: prices = [1]
Output: 0
A single day allows no trade.

Constraints

  • 1 <= prices.length <= 5000
  • 0 <= prices[i] <= 1000

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More 1d dp problems