DSA interview question
A stock analyst has the daily price changes for a year (some days up, some down) and wants the best stretch of consecutive days to have held the stock, meaning the contiguous subarray with the largest total. Trying every start and end is O(n²). Kadane's algorithm scans once, keeping the best sum of a subarray ending at the current day: either extend yesterday's best run, or start fresh today if yesterday's run was dragging the total down.
Example: [-2, 1, -3, 4, -1, 2, 1, -5, 4] → 6 (the subarray [4, -1, 2, 1]).
long long maxSubArray(const vector<int>& nums); // largest sum of a non-empty contiguous subarray
Input nums | Output | Explanation |
|---|---|---|
[-2, 1, -3, 4, -1, 2, 1, -5, 4] | 6 | [4, -1, 2, 1] |
[1] | 1 | |
[5, 4, -1, 7, 8] | 23 | The whole array |
[-3, -1, -2] | -1 | All negative: the best is the single largest element |
[0, -1, 0] | 0 |
(Confirm: the subarray must be non-empty, so an all-negative array returns its largest element, not 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