DSA interview question
You're extending the trading bot backend from before, but now the compliance team has imposed a hard cap: the bot is only allowed to execute at most k transactions (a transaction = one buy followed by one sell) in the given trading window. Given an array prices where prices[i] is the stock price on day i, and an integer k, return the maximum profit achievable with at most k transactions. You can hold at most one share at a time (must sell before buying again).
int maxProfit(int k, vector<int>& prices);
Input k | Input prices | Output | Explanation |
|---|---|---|---|
2 | [2,4,1] | 2 | Buy@2, sell@4 (profit 2); second transaction not worth it |
2 | [3,2,6,5,0,3] | 7 | Buy@2, sell@6 (profit 4), buy@0, sell@3 (profit 3) → total 7 |
1 | [7,1,5,3,6,4] | 5 | Buy@1, sell@6 (profit 5), only 1 transaction allowed |
0 | [1,2,3,4,5] | 0 | No transactions allowed |
100 | [1,2,3,4,5] | 4 | k is large relative to array — behaves like unlimited transactions |
2 | [] | 0 | Empty array |
3 | [1] | 0 | Single day — no transaction possible |
(Always check the case where k is very large relative to n/2 — that's a classic optimization trap discussed below.)
k buy-sell transactions. Maximize profit."k relative to n (array length)? This matters a lot — if k >= n/2, the problem collapses to the unlimited-transactions case.k be 0?k potentially very large (e.g., up to 10^9)? This affects whether the O(nk) DP is feasible or whether you need the greedy fallback for large k.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