Skip to the solution
MediumDSA11 min read

How do you find the maximum subarray sum?

819 views

The problem

Question presented to candidate: "Given an integer array, find the contiguous subarray with the largest sum and return that sum. Code it in Python. What if every number is negative? Can you also return where the subarray starts and ends?"

What a strong answer should cover:

  • The state "best sum of a subarray ending here" and the update cur = max(x, cur + x), best = max(best, cur) β€” Kadane, O(n) time, O(1) space.
  • Why a negative running sum should be dropped, and that the two forms (restart if cur < 0 / max(x, cur + x)) are the same rule.
  • Initialising from the first element so all-negative arrays return their largest element, not 0.
  • The brute-force baselines (O(nΒ³), O(nΒ²)) and the prefix-sum view; tracking start and end indices.
  • Python specifics: starting from nums[0] rather than 0 or float("-inf"), IndexError on an empty list, slicing being end-exclusive for returning the subarray, and int never overflowing.

Clarifying questions expected:

  • "Must the subarray be non-empty, and what should an empty input return?"
  • "Do you want the sum only, or the indices too?"

Code / implementation expected: Yes β€” a one-pass Python function, with indices as a follow-up.

  • kadane
  • dp

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

11 min read Β· 12 sections

Python code

Edit the code and run it here. Each printed line with an expected value becomes a test.

PythonKadane with the winning subarray and its indices, against the start-at-zero bug
PythonFour methods side by side: O(n^3), O(n^2), prefix sums and Kadane, with addition counts

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 63 of 154 in DSA

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All DSA questions
Up nextMedium

Find the kth largest element in an array

Continue