DSA interview question
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).
int maxProfit(vector<int>& prices);
Input prices | Output | Explanation |
|---|---|---|
[3,3,5,0,0,3,1,4] | 6 | Buy@0, sell@3 (profit 3), then... verify: buy@3,sell@5(2), buy@0,sell@4(4) → 6 |
[1,2,3,4,5] | 4 | One transaction (buy@1, sell@5) is optimal — second doesn't help |
[7,6,4,3,1] | 0 | Strictly decreasing — no profitable trade |
[1] | 0 | Single day — no transaction possible |
[] | 0 | Empty array |
[1,2,4,2,5,7,2,4,9,0] | 13 | Buy@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.)
prices? (Confirms O(n) time with O(1) space is expected here, since k is fixed and small.)buy1 initialized to negative infinity (or -prices[0]) but sell1/sell2 to 0?"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 interviewAll 474 dsa interview questions
DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in