Quick Answer

Find the maximum subarray in 3 ways. Use brute force, divide and conquer or the Kadane algorithm. Brute force checks every stretch and costs O(n²). Divide and conquer splits the array and costs O(n log n). Kadane algorithm scans once and costs O(n). Start both sums at the first item and not at zero. Test your code on an array with only negative numbers.

Maximum subarray is the problem of finding the stretch of an array with the largest sum. Items in the stretch must sit side by side in the original order. In [3, -4, 5, -1, 2, -5, 4] the answer is 6 from the items 5, -1 and 2.

Python code solves the maximum subarray problem in 3 ways and a trace table follows the one pass method item by item.

You also see the zero start bug, which gives a wrong maximum subarray answer when every number is negative.

What Is the Maximum Subarray Problem?

You get an array of integers and you must find one stretch with the largest sum. LeetCode lists the task as Maximum Subarray, problem 53.

Subarray means a stretch of items that sit side by side. Subsequence can jump over items and subarray cannot. Check arrays in data structure first if arrays are new to you.

Take the sample array [3, -4, 5, -1, 2, -5, 4]. Five stretches and their sums appear in the table.

StretchSum
33
3, -4, 54
5, -1, 26
5, -1, 2, -5, 45
3, -4, 5, -1, 2, -5, 44

Stretch 5, -1, 2 gives the largest sum of 6. No other stretch of this array reaches 6.

Do You Know? Items 3, 5 and 4 of the sample array sum to 12. They are not side by side so they form a subsequence and not a subarray.

Which 3 Methods Solve the Maximum Sum Subarray Problem?

Three methods solve maximum subarray and they differ in time. Compare them in the table below.

MethodTimeExtra spaceUse case
Brute forceO(n²)O(1)Checking small tests
Divide and conquerO(n log n)O(log n)Practising recursion
Kadane algorithmO(n)O(1)Final answers in one pass

Method #1: Brute Force (Slow, Good for Checking)

Who it suits. Beginners who want a correct answer to check faster code. Extra application. None, because a Python install is enough.

Brute force finds the maximum subarray by starting at every index and adding items one by one while tracking the largest sum.

def max_subarray_brute(nums):
    best = nums[0]
    for start in range(len(nums)):
        total = 0
        for end in range(start, len(nums)):
            total += nums[end]
            best = max(best, total)
    return best

print(max_subarray_brute([3, -4, 5, -1, 2, -5, 4]))   # prints 6

Two loops check every start and end pair, which costs O(n²) time. Arrays with 100,000 items need about 5 billion additions.

Method #2: Divide and Conquer (Medium Speed, Good Practice)

Who it suits. Learners who practise recursion. Extra application. None, because any Python setup works.

Divide and conquer splits the array at the middle to find the maximum subarray. Answer stretch sits fully in the left half or fully in the right half or across the middle.

Crossing stretch adds the largest sum that ends at the middle on the left to the largest sum that starts after the middle on the right. Open the recursion lesson for the call pattern.

def max_subarray_split(nums, low, high):
    if low == high:
        return nums[low]
    mid = (low + high) // 2
    left_best = max_subarray_split(nums, low, mid)
    right_best = max_subarray_split(nums, mid + 1, high)
    total, left_edge = 0, float("-inf")
    for i in range(mid, low - 1, -1):
        total += nums[i]
        left_edge = max(left_edge, total)
    total, right_edge = 0, float("-inf")
    for i in range(mid + 1, high + 1):
        total += nums[i]
        right_edge = max(right_edge, total)
    return max(left_best, right_best, left_edge + right_edge)

print(max_subarray_split([3, -4, 5, -1, 2, -5, 4], 0, 6))   # prints 6

Every level of the recursion scans the array once. Halving happens about log n times. Time is O(n log n).

Method #3: Kadane Algorithm (Recommended, One Pass)

Who it suits. Anyone who needs the final answer in one pass. Extra application. None, because Python alone is enough.

Kadane algorithm finds the maximum subarray with one choice at every item. Extend the stretch that ends at the item before or restart at the current item. Larger sum wins.

Two variables track the work. Variable current stores the largest sum of a stretch that ends at the current item. Variable best stores the largest sum seen anywhere.

def kadane(nums):
    current = best = nums[0]
    for value in nums[1:]:
        current = max(value, current + value)
        best = max(best, current)
    return best

print(kadane([3, -4, 5, -1, 2, -5, 4]))   # prints 6

Trace table below follows the algorithm on [3, -4, 5, -1, 2, -5, 4].

IndexItemExtendRestartCurrentBest
03startstart33
1-4-1-4-13
254555
3-14-145
426266
5-51-516
645456

Index 2 shows the restart move. Extending gives 4 and restarting gives 5, which is larger. Method #3 drops the old stretch and begins again at 5.

Largest sum 6 appears at index 4 and remains the answer to the end. Method #3 visits every item once and stores two numbers. Time is O(n) and space is O(1).

Method #3 is a small dynamic programming idea because the answer at one item depends on the answer at the item before. Learn why O(n) beats O(n²) in the time complexity and Big O post.

How to return the start and end. Store the start index when the code restarts. Store both indices when best grows.

def kadane_range(nums):
    current = best = nums[0]
    start = best_start = best_end = 0
    for i in range(1, len(nums)):
        if nums[i] > current + nums[i]:
            current = nums[i]
            start = i
        else:
            current += nums[i]
        if current > best:
            best = current
            best_start, best_end = start, i
    return best, best_start, best_end

print(kadane_range([3, -4, 5, -1, 2, -5, 4]))   # prints (6, 2, 4)

Indices 2 to 4 point to the stretch 5, -1, 2.

Why Does Starting at Zero Break the Maximum Subarray Answer?

Many short versions of the Kadane algorithm set both variables to 0 at the start. Zero start code works when the array has at least one positive number.

def kadane_zero_start(nums):
    current = best = 0
    for value in nums:
        current = max(0, current + value)
        best = max(best, current)
    return best

print(kadane_zero_start([-5, -2, -8, -3]))   # prints 0

Correct maximum subarray answer for [-5, -2, -8, -3] is -2 because the stretch must have at least one item. Zero start code returns 0, which no stretch of those items can reach.

CodeResult for [-5, -2, -8, -3]Correct?
Zero start version0No
First item start version-2Yes
Brute force-2Yes

Fix is one line. Start both variables at nums[0] as Method #3 does.

Heads Up. Test every copied version of Kadane algorithm with an array of only negative numbers. Zero start versions fail that test.

Some versions of the problem allow an empty stretch. Then 0 is correct for that array. Check the problem statement before you choose the start value.

Can Sliding Window Find the Max Sum Subarray?

Not with the usual rules. Standard sliding window shrinks the window when the sum passes a limit. That rule needs every number to push the sum in one direction.

Negative numbers break that rule. Adding a negative item lowers the sum but a later large item can raise the sum again.

Method #3 works like a window with a jumping left edge. Every restart moves the left edge to the current item. Extending moves only the right edge.

Use the sliding window technique for sums of a set size. Watch the Max Sum Window visualiser to see a fixed window move.

Frequently Asked Questions

Is the Kadane Algorithm a Dynamic Programming Method?

Yes. Kadane algorithm builds the answer at one item from the answer at the item before. Space is O(1) because the code stores two numbers. Extend or restart also looks greedy because the code takes the larger move at every item.

Does the Maximum Subarray Need Items Side by Side?

Yes. Subarray means an unbroken stretch of the original array. Subsequence can jump over items, which makes it a different problem with a different answer.

Does Method #3 Work When Every Number Is Negative?

Yes, when both variables begin at the first item. Largest single number is then the answer. For [-5, -2, -8, -3] the answer is -2.

Is Method #3 Faster Than Divide and Conquer?

Yes. Method #3 takes O(n) time and divide and conquer takes O(n log n) time. Divide and conquer also needs O(log n) extra space for the recursion.

Can You Return the Subarray and Not Only the Sum?

Yes. Store the start index at every restart and store both indices when the largest sum grows. For the maximum subarray of [3, -4, 5, -1, 2, -5, 4] indices 2 to 4 give the stretch 5, -1, 2.

Can Two Stretches Share the Same Maximum Subarray Sum?

Yes. In [2, -2, 2] the first item, the last item and the full array all sum to 2. Code in this post uses a strict greater than test and returns the first stretch it finds.

Can You Check Method #3 With Brute Force?

Yes. Execute both functions on small arrays and compare the results. Two answers must match on every array, including arrays with only negative numbers.

What Should You Remember About Maximum Subarray?

Kadane algorithm solves maximum subarray in O(n) time and O(1) space. Start both variables at the first item and choose extend or restart at every item. Brute force and divide and conquer remain useful for testing.

Key takeaways.

  • Maximum subarray asks for the stretch with the largest sum.
  • Zero start code fails on an array of only negative numbers.
  • Sliding window needs a jumping left edge to match Method #3.

Practice question. Find the maximum subarray sum of [-3, 4, -1, 2, -6, 1]. Answer. 5, from the stretch 4, -1, 2.

Open the array practice problems to solve more.