Maximum Subarray solution explained

The Maximum Subarray solution interviewers look for is Kadane's algorithm: walk the array once, and at each position keep the best sum of a slice that ends exactly there, which is either the current value alone or the current value added to the previous best. The largest of those running values is the answer, found in O(n) time and O(1) space.

By Published 7 min read

What you are asked to find

Take an array of integers, some possibly negative. A subarray is a stretch of one or more entries that sit next to each other, with nothing skipped. Among all such stretches, find the one whose entries add up to the most and return that sum. The stretch must contain at least one entry, so the answer for an array of only negative numbers is its least negative value, not zero.

Arrays written for this walkthrough
ArrayLargest sumThe winning slice
[2, -4, 6, -3, 5, -9, 4]8[6, -3, 5]: the -3 is worth crossing to reach the 5
[2, 3, -1, 4]8The whole array
[-7, -2, -9]-2A single entry, since every longer slice is worse
[0, -3, 0]0Either zero on its own
Arrays written for this walkthrough. Scroll sideways on a small screen.

Clarify before you start: must the slice be non-empty, or may you return 0 for choosing nothing? Do you need the sum only, or the start and end too? How large can the values get? The first question changes the answer for all-negative arrays, so it is the one interviewers most hope you ask.

What the question reveals

This is often a candidate's first real dynamic programming problem in disguise. The interviewer wants to see you define a subproblem (the best sum of a slice ending at index i), write how it depends on the previous one, and then notice that only one previous value is needed, so the table collapses to a single variable. Candidates who memorized the loop without that reasoning usually struggle when the follow-up changes sums to products.

Follow-up questions to prepare

  • Return the slice, not just the sum. Remember where the current run started, and copy the start and end whenever the best improves.
  • The array wraps around. The best circular slice is either an ordinary slice or the total minus the smallest ordinary slice. If every value is negative, the second option would select nothing, so fall back to the ordinary answer.
  • Largest product instead of sum. A negative times a negative turns small into large, so carry both the largest and the smallest product ending at each index.
  • Slices of at least k entries. Combine prefix sums with the smallest prefix seen at least k positions back.
  • A two-dimensional grid. Fix a pair of rows, collapse the columns between them into one array of sums, and run Kadane on it. That is O(rows² × columns).

Brute force: try every start and every end

Pick each possible start, then extend the end one step at a time while keeping a running total, and record the largest total you see. Reusing the running total avoids re-adding the slice each time, so this is O(n²) rather than O(n³). It is the version to say first and the one to test against.

def best_slice_sum_slow(values):
    best = values[0]
    for start in range(len(values)):
        running = 0
        for end in range(start, len(values)):
            running += values[end]
            best = max(best, running)
    return best
Every start and end with a running total, O(n²) time and O(1) space.

Optimal approach: Kadane's algorithm

Define ending_here as the largest sum of a slice that ends exactly at the current index. There are only two candidates for it: the current value by itself, or the current value tacked onto the best slice that ended one step earlier. Take whichever is larger. If the previous run had a negative total, it can only hurt, so the run restarts at the current value. The overall answer is the largest ending_here you ever see.

Initializing both variables with the first entry, rather than with 0, is what keeps an all-negative array correct. Starting from 0 silently allows an empty slice and returns 0 for [-7, -2, -9].

def best_slice_sum(values):
    ending_here = best = values[0]
    for v in values[1:]:
        ending_here = max(v, ending_here + v)
        best = max(best, ending_here)
    return best
Python: Kadane's algorithm, O(n) time and O(1) space. Assumes a non-empty array.
function bestSliceSum(values) {
  let endingHere = values[0];
  let best = values[0];
  for (let i = 1; i < values.length; i++) {
    endingHere = Math.max(values[i], endingHere + values[i]);
    best = Math.max(best, endingHere);
  }
  return best;
}
JavaScript: the same scan with an index loop, which avoids copying the array.

The Python slice values[1:] makes a copy, which costs O(n) memory. If the interviewer is strict about constant space, loop over indexes instead, as the JavaScript version does.

def best_slice_with_bounds(values):
    ending_here, run_start = values[0], 0
    best, bounds = values[0], (0, 0)
    for i in range(1, len(values)):
        if ending_here < 0:
            ending_here, run_start = values[i], i
        else:
            ending_here += values[i]
        if ending_here > best:
            best, bounds = ending_here, (run_start, i)
    return best, bounds
Follow-up: also return where the best slice starts and ends (inclusive indexes).
def best_circular_sum(values):
    hi = lo = ending_hi = ending_lo = values[0]
    for v in values[1:]:
        ending_hi = max(v, ending_hi + v)
        ending_lo = min(v, ending_lo + v)
        hi = max(hi, ending_hi)
        lo = min(lo, ending_lo)
    if hi < 0:
        return hi  # all negative: wrapping would mean taking nothing
    return max(hi, sum(values) - lo)
Follow-up: circular array. Best ordinary slice, or everything except the worst slice.

Complexity

Approaches compared
ApproachTimeExtra spaceComment
Every slice, summed from scratchO(n³)O(1)Only worth naming
Every slice with a running totalO(n²)O(1)The brute force to write
Divide and conquer on the midpointO(n log n)O(log n) recursionA classic alternative, sometimes asked as a follow-up
Kadane's algorithmO(n)O(1)The expected answer
Circular versionO(n)O(1)Max of best slice and total minus worst slice
Approaches compared. Scroll sideways on a small screen.

Edge cases to try

  • Every value negative: the answer is the single largest value.
  • A single entry, negative or positive.
  • Zeros mixed with negatives, such as [0, -3, 0].
  • The whole array is the best slice, as in [2, 3, -1, 4].
  • A big negative splits two good runs, as in [5, -20, 6]: the right answer is 6, not 5 + 6.
  • An empty array: decide with the interviewer, since the usual version rules it out and the code above assumes at least one entry.

Common errors

  • Starting the best sum at 0, which turns every all-negative array into a wrong 0.
  • Clamping the running sum at 0 after each step, a variant that quietly permits an empty slice and so also answers 0 for an all-negative array.
  • Updating the best before updating ending_here, which lags one step behind and misses the last element's contribution.
  • In the circular follow-up, returning total minus the minimum when all values are negative, which yields 0 from an empty selection.
  • Describing Kadane as greedy without explaining the subproblem. Interviewers want the recurrence, not just the loop.

How to explain it out loud

Fictional example

A clear spoken version of Kadane's idea
Candidate
Checking every start and end is quadratic. Instead I ask, for each index, what the best slice ending right here is.
Candidate
That slice either starts fresh at this value or extends the best slice ending one step back. If that earlier run is negative, starting fresh wins. I keep the best of these as I go, so one pass and two variables.
Candidate
On 2, -4, 6, -3, 5, -9, 4 the run restarts at 6, dips to 3 at the -3, reaches 8 at the 5, and nothing later beats 8.

Connected problems

Best Time to Buy and Sell Stock is this problem in costume: run Kadane over the day-to-day price changes and clamp the result at 0. Climbing Stairs is another one-variable-per-step recurrence, and Product of Array Except Self builds running products from each side. For a window that slides instead of restarting, compare with Longest Substring Without Repeating Characters. The rest are on the coding problems hub.

Working through it with Natively

Practicing dynamic programming goes better when you can compare your recurrence with a second opinion. Natively, on Mac or Windows, can read a problem like this from a screenshot during practice and suggest Kadane's approach with code and the all-negative test. It also transcribes your mock session, so you can check later whether you stated the subproblem before you wrote the loop. Read about an AI interview assistant for this kind of preparation.

Questions people ask

What is Kadane's algorithm?

A one-pass method for the largest sum of a contiguous slice. At each index it keeps the best sum of a slice ending there, which is the current value or the current value plus the previous best, and tracks the largest of those.

What is the time complexity of Maximum Subarray?

O(n) time and O(1) extra space with Kadane's algorithm. Trying every start and end with a running total is O(n²), and a divide-and-conquer version is O(n log n).

What if every number in the array is negative?

The answer is the largest single value, because the slice must hold at least one entry. Start the running and best sums at the first element, not at 0, or the code returns 0.

Is Maximum Subarray a dynamic programming problem?

Yes. The subproblem is the best sum of a slice ending at index i, it depends only on the answer for i - 1, and so the table shrinks to one variable.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP