Skip to the solution
MediumDSA11 min read

Maximum subarray (Kadane) vs divide-and-conquer — proof of correctness?

906 views

The problem

Question presented to candidate: "You know Kadane's algorithm for the maximum subarray sum. Can you prove it is correct? Then describe a divide-and-conquer algorithm for the same problem, prove that one too, and compare them. Sketch both in Python."

What a strong answer should cover:

  • Kadane's loop invariants (best sum ending at i, best so far) with initialisation, maintenance and termination, and the lemma E(i) = max(a[i], E(i-1) + a[i]) proved by an exchange argument.
  • Divide and conquer: the left / right / crossing case split, why the crossing sum is best suffix + best prefix, and the strong-induction proof.
  • Costs: T(n) = 2T(n/2) + O(n) = O(n log n) for the crossing version versus O(n) and O(1) space for Kadane.
  • The four-value (total, prefix, suffix, best) combine that makes divide and conquer O(n) and becomes a segment tree for range queries.
  • Python specifics: (lo + hi) // 2 is safe because ints do not overflow, recursion depth is only about log₂ n, and passing bounds instead of slicing avoids copies.

Code / implementation expected: Optional — the proofs matter most; a Python sketch of the crossing-sum recursion and Kadane's loop is a strong finish.

  • dp
  • array
  • Amazon

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.

PythonCrossing-sum divide and conquer, four-value divide and conquer and Kadane: answers and work counted
PythonKadane loop invariants checked against brute force at every step

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 55 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

Implement Trie for autocomplete — how do you handle wildcards (.)?

Continue