DSA interview question
Your trading bot backend just got its most relaxed ruleset yet — no fee, no cooldown, no transaction limit. Given an array prices where prices[i] is the stock price on day i, you can buy and sell as many times as you want, but you must hold at most one share at a time (sell before buying again). Return the maximum profit achievable.
int maxProfit(vector<int>& prices);
Input prices | Output | Explanation |
|---|---|---|
[7,1,5,3,6,4] | 7 | Buy@1,sell@5 (4), buy@3,sell@6 (3) → total 7 |
[1,2,3,4,5] | 4 | Buy@1, sell@5 — one continuous uptrend, capture the whole rise |
[7,6,4,3,1] | 0 | Strictly decreasing — no profitable trade |
[1] | 0 | Single day — no transaction possible |
[] | 0 | Empty array |
[1,7,2,3,6,7,6,7] | 13 | Buy@1,sell@7(6), buy@2,sell@3(1), buy@6,sell@7(1)... verify total with code |
(Always verify: with unlimited transactions and no fee, capturing every single positive day-to-day delta is always optimal — confirm this intuition matches brute force before trusting the greedy.)
prices? (Confirms O(n) greedy is expected, not something more complex.)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