DSA interview question
This is the foundational version of your trading bot backend, before any of the fee/cooldown/k-transaction rules existed. Given an array prices where prices[i] is the stock price on day i, you're allowed to complete at most one transaction (buy on one day, sell on a later day). Return the maximum profit you can achieve. If no profit is possible, return 0.
int maxProfit(vector<int>& prices);
Input prices | Output | Explanation |
|---|---|---|
[7,1,5,3,6,4] | 5 | Buy@1, sell@6 → profit 5 |
[7,6,4,3,1] | 0 | Strictly decreasing — no profitable trade, return 0 |
[1,2,3,4,5] | 4 | Buy@1, sell@5 → profit 4 |
[1] | 0 | Single day — no transaction possible |
[] | 0 | Empty array |
[2,4,1] | 2 | Buy@2, sell@4 → profit 2 (buying at 1 comes too late to sell higher) |
[3,3,3,3] | 0 | No price movement — no profit possible |
(Always check: you must buy before you sell — selling can never happen on an earlier or same day as buying.)
prices[j] - prices[i] for j > i?"prices? (Confirms O(n) is expected over O(n²) brute force.)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