PPractick

DSA interview question

Best Time to Buy and Sell Stock with Cooldown

Medium · Algorithms · Topics: dynamic programming, array, state machine

The problem

Your trading bot's compliance module now has a new rule from the exchange: after selling a stock, the bot must wait one full day (a "cooldown") before it's allowed to buy again — this mimics a real-world T+1 settlement restriction. Given an array prices where prices[i] is the stock price on day i, you can buy and sell as many times as you want (holding at most one share at a time), but after each sell, you cannot buy on the very next day. Return the maximum profit achievable under this constraint.

Function signature

int maxProfit(vector<int>& prices);

Test cases

Input pricesOutputExplanation
[1,2,3,0,2]3Buy@1, sell@2 (profit 1), cooldown day, buy@0, sell@2 (profit 2) → total 3
[1]0Single day — no transaction possible
[]0Empty array
[1,2,4]3Buy@1, sell@4 — one transaction beats splitting since cooldown wastes a day
[6,1,3,2,4,7]6Buy@1, sell@3 (profit 2), cooldown, buy@2, sell@7 (profit 5)... verify best combo with code
[7,6,4,3,1]0Strictly decreasing — no profitable trade
[2,1,4]3Buy@1, sell@4

(Always verify with the code output since cooldown interactions can be non-obvious to compute by hand.)

How interviewers phrase it

Clarifying questions to ask

  1. Does cooldown mean exactly one day of forced inactivity after a sell, or could it be a parameterized number of days?
  2. Can I hold at most one share at a time (must sell before buying again)?
  3. Is there a transaction fee as well, or is this purely the cooldown constraint in isolation?
  4. What's the expected size of prices? (Confirms whether O(n) with O(1) space is expected, or O(n) with O(n) space is acceptable.)
  5. Are prices non-negative integers?

Follow-ups to expect

  1. "Can you do this in O(1) space?"
  2. "What if the cooldown period is a variable number of days, not just 1?"
  3. "What if there's also a transaction fee, combined with the cooldown?"
  4. "How does this compare to Stock II (no cooldown)?"
  5. "Can you draw the state transition diagram from memory?"
  6. "What if you're also limited to at most k transactions, combined with cooldown?"

Practise questions like this with a real engineer

On Practick another engineer interviews you live for 60 minutes on a question from this bank. They have the full interviewer guide beside the call: the expected answer to every follow-up, hints to give if you stall, and a scoring rubric. You get the model solution once the session settles. It is free: interview someone for an hour and you have earned your own.

Book a free mock interview

Related questions

All 474 dsa interview questions

DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in