PPractick

DSA interview question

Maximum Subarray Sum (Kadane's Algorithm)

Medium · Algorithms · Topics: array, dynamic programming, greedy

The problem

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]).

Function signature

long long maxSubArray(const vector<int>& nums);  // largest sum of a non-empty contiguous subarray

Test cases

Input numsOutputExplanation
[-2, 1, -3, 4, -1, 2, 1, -5, 4]6[4, -1, 2, 1]
[1]1
[5, 4, -1, 7, 8]23The whole array
[-3, -1, -2]-1All 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.)

How interviewers phrase it

Clarifying questions to ask

  1. Must the subarray be non-empty? (Decides the all-negative case.)
  2. Return the sum, or the start and end indices?
  3. How large can the values be? (Use 64-bit sums.)

Follow-ups to expect

  1. "What's the recurrence?"
  2. "Why reset when the running sum goes negative?"
  3. "What about an all-negative array?"
  4. "How do you recover the subarray?"
  5. "Is there a divide-and-conquer solution?"
  6. "Complexity?"

Practise questions like this with a real engineer

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 interview

Related questions

All 474 dsa interview questions

DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in