DSA interview question
A trading app offers a "perfect hindsight" feature: given a stock's daily prices, show the maximum profit from one buy followed by one later sell. If prices only fall, the best choice is not to trade, for a profit of 0. Checking every buy/sell pair is O(n²). The one-pass insight: if you sell on day i, the best buy day is simply the cheapest day before it, so track the minimum price so far and the best profit so far.
Example: [7, 1, 5, 3, 6, 4] → 5 (buy at 1, sell at 6).
int maxProfit(const vector<int>& prices); // one transaction; 0 if no profit is possible
Input prices | Output | Explanation |
|---|---|---|
[7, 1, 5, 3, 6, 4] | 5 | Buy at 1 (day 1), sell at 6 (day 4) |
[7, 6, 4, 3, 1] | 0 | Prices only fall: don't trade |
[2, 4, 1] | 2 | The later minimum (1) comes too late to help |
[1] | 0 | Can't buy and sell on the same day |
[3, 3, 3] | 0 | |
[2, 1, 2, 1, 0, 1, 2] | 2 | Buy at 0, sell at 2 |
(Confirm: exactly one buy and one later sell, or no trade at all.)
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