L2 · Working engineerLists & arrays~12 min · 5 tests#10

Maximum Subarray Sum (Kadane's Algorithm)

Find the largest sum of any contiguous subarray with Kadane's algorithm in O(n). Compare with the O(n²) brute force using the live Complexity Lab.

The problem

Return the largest possible sum of a contiguous, non-empty subarray of nums.

If every number is negative, the answer is the largest single number.

Examples

  1. Example 1

    Input

    max_subarray([-2, 1, -3, 4, -1, 2, 1, -5, 4])

    Expected output

    6
  2. Example 2

    Input

    max_subarray([1, 2, 3])

    Expected output

    6

+ 3 hidden tests on Submit — all negative, single element, restart beats extend.

Edge cases to ask about

  • All negative
  • Single element
  • Large positive after a big negative

Hints

0/3

    How an interviewer scores this

    0/9
    Python 3.13 · max_subarray
    ⌘/Ctrl + Enter runs the examples

    Your code runs in real CPython inside your browser — nothing is sent anywhere. The first run downloads the interpreter (about 6 MB, once). Your code is saved on this device as you type.

    Complexity Lab

    What does this cost as n grows?

    Interviewers score the analysis as much as the code. Commit to an answer first — then check it, and measure your code against the optimal one at growing input sizes.

    Time complexity of the optimal solution
    Space complexity (extra memory)

    Pick both to reveal the answer.

    Measure it

    Runs the function on inputs of size 250 up to 16,000 and records the time and peak memory. Slow solutions stop early — a short curve is itself the answer.

    From brute force to optimal

    The progression an interviewer wants to hear, one step at a time.

    ApproachTimeSpaceIdea
    Every start × every endO(n²)O(1)Running total from each start index.
    bestKadane's algorithmO(n)O(1)At each element, either extend the current run or start fresh — whichever is larger.
    Walkthrough of the optimal approach (try it yourself first)

    Kadane's insight: the best subarray ending at position i is either nums[i] alone, or the best subarray ending at i − 1 plus nums[i]. A negative running sum can only hurt, so you drop it and restart.

    Track current (best ending here) and best (best anywhere). Start both at nums[0], not 0, so an all-negative list returns its largest element.

    Complexity: O(n) time, O(1) space. One pass; at every step only the best-ending-here and best-overall values are kept.

    Reveal the reference solution
    def max_subarray(nums):
        best = current = nums[0]
        for x in nums[1:]:
            current = max(x, current + x)
            best = max(best, current)
        return best

    The brute force, for comparison

    def max_subarray(nums):
        best = nums[0]
        for i in range(len(nums)):
            total = 0
            for j in range(i, len(nums)):
                total += nums[j]
                best = max(best, total)
        return best

    Follow-ups interviewers ask

    • Return the start and end indices too.
    • Maximum product subarray (sign flips!).

    Frequently asked interview questions

    Core interview concepts, complexities, and follow-ups scored by hiring teams.

    What is the time complexity of Maximum Subarray Sum (Kadane's Algorithm) in Python?

    The optimal solution runs in O(n) time and O(1) auxiliary space. One pass; at every step only the best-ending-here and best-overall values are kept.

    What is the brute-force approach, and how do you optimise it?

    Every start × every end: O(n²) time, O(1) space. Running total from each start index. Kadane's algorithm: O(n) time, O(1) space. At each element, either extend the current run or start fresh — whichever is larger.

    What follow-up questions do interviewers ask about Maximum Subarray Sum (Kadane's Algorithm)?

    Return the start and end indices too. Maximum product subarray (sign flips!).