PPractick

DSA interview question

Best Time to Buy and Sell Stock III

Medium · Algorithms · Topics: dynamic programming, array

The problem

Your trading bot's compliance team has now imposed a stricter cap than before: instead of an arbitrary k, the bot is limited to at most two transactions total in the given trading window. Given an array prices where prices[i] is the stock price on day i, return the maximum profit achievable with at most two buy-sell transaction pairs. You can hold at most one share at a time (must sell before buying again).

Function signature

int maxProfit(vector<int>& prices);

Test cases

Input pricesOutputExplanation
[3,3,5,0,0,3,1,4]6Buy@0, sell@3 (profit 3), then... verify: buy@3,sell@5(2), buy@0,sell@4(4) → 6
[1,2,3,4,5]4One transaction (buy@1, sell@5) is optimal — second doesn't help
[7,6,4,3,1]0Strictly decreasing — no profitable trade
[1]0Single day — no transaction possible
[]0Empty array
[1,2,4,2,5,7,2,4,9,0]13Buy@1,sell@7 (6), buy@2,sell@9 (7) → total 13

(Always verify tricky ones like [3,3,5,0,0,3,1,4] with the code — hand-tracing two-transaction cases is error-prone.)

How interviewers phrase it

Clarifying questions to ask

  1. Can I hold at most one share at a time (must sell before buying again)?
  2. Does "at most two transactions" mean I could also do zero or one if that's more profitable, or must I do exactly two?
  3. What's the expected size of prices? (Confirms O(n) time with O(1) space is expected here, since k is fixed and small.)
  4. Are prices non-negative integers?
  5. Should I design this as a special case, or should I be ready to generalize to Stock IV afterward?

Follow-ups to expect

  1. "Can you do this in O(1) space?"
  2. "Can you generalize this to at most k transactions?"
  3. "What if there's also a transaction fee?"
  4. **"Can you prove why processing buy1
  5. "What if cooldown is also required between transactions?"
  6. "Why is buy1 initialized to negative infinity (or -prices[0]) but sell1/sell2 to 0?"

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