Skip to main content
1:1 mock interviews with Sumit, scored on a real hiring rubric.Book a slot →

Kadane's Algorithm: Maximum Subarray Sum in O(n) Explained

Learn Kadane's algorithm for the maximum subarray problem: brute force to O(n), step-by-step trace, all-negative arrays, returning indices, maximum product subarray, circular subarrays and the dynamic programming idea behind it.

Sumit KumarUpdated Oct 11, 20265 min readDSA
Kadane's Algorithm: Maximum Subarray Sum in O(n) Explained

The maximum subarray problem asks: given an array of integers, which contiguous subarray has the largest sum? For [-2, 1, -3, 4, -1, 2, 1, -5, 4] the answer is [4, -1, 2, 1] with sum 6. Kadane's algorithm solves it in a single pass with O(1) extra memory, and it's one of the best introductions to dynamic programming.

From brute force to O(n)#

Brute force: O(n²)#

Python
def max_subarray_brute(nums):
    best = float("-inf")
    for i in range(len(nums)):
        total = 0
        for j in range(i, len(nums)):
            total += nums[j]          # sum of nums[i..j]
            best = max(best, total)
    return best

This checks every subarray. For 100,000 elements that's about 5 billion additions: far too slow.

The key insight#

At each index, the best subarray ending here either:

  • extends the best subarray ending at the previous index, or
  • starts fresh at this element.

If the running sum so far is negative, it can only drag the total down, so you drop it and start over.

Text
current[i] = max(nums[i], current[i-1] + nums[i])
best       = max(best, current[i])

Kadane's algorithm#

Python
def max_subarray(nums: list[int]) -> int:
    current = best = nums[0]
    for x in nums[1:]:
        current = max(x, current + x)   # extend or restart
        best = max(best, current)
    return best

print(max_subarray([-2, 1, -3, 4, -1, 2, 1, -5, 4]))   # 6
Java
public int maxSubArray(int[] nums) {
    int current = nums[0], best = nums[0];
    for (int i = 1; i < nums.length; i++) {
        current = Math.max(nums[i], current + nums[i]);
        best = Math.max(best, current);
    }
    return best;
}
JavaScript
function maxSubArray(nums) {
  let current = nums[0], best = nums[0];
  for (let i = 1; i < nums.length; i++) {
    current = Math.max(nums[i], current + nums[i]);
    best = Math.max(best, current);
  }
  return best;
}

Step-by-step trace#

Kadane's algorithm trace on an array: running current sum and best sum at each index, resetting when the current sum turns negative
inums[i]current = max(x, current + x)best
0-2-2-2
11max(1, -1) = 1 (restart)1
2-3max(-3, -2) = -21
34max(4, 2) = 4 (restart)4
4-1max(-1, 3) = 34
52max(2, 5) = 55
61max(1, 6) = 66
7-5max(-5, 1) = 16
84max(4, 5) = 56

Handling all-negative arrays#

A popular "simplified" version resets current to 0 whenever it goes negative:

Python
current = best = 0
for x in nums:
    current = max(0, current + x)
    best = max(best, current)
# returns 0 for [-3, -1, -2]  ← wrong if the subarray must be non-empty
Edge case

If the subarray must contain at least one element, the answer for [-3, -1, -2] is -1. Initialise both variables with nums[0], as in the main version above, and this case works automatically.

Returning the subarray itself#

Python
def max_subarray_with_indices(nums):
    best = current = 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                     # a new subarray begins here
        else:
            current += nums[i]
        if current > best:
            best, best_start, best_end = current, start, i
    return best, nums[best_start:best_end + 1]

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

Why it's dynamic programming#

Define dp[i] = the maximum sum of a subarray that ends at index i. Then:

Text
dp[0] = nums[0]
dp[i] = max(nums[i], dp[i-1] + nums[i])
answer = max(dp)

Since each dp[i] only depends on dp[i-1], you don't need the whole array: a single variable is enough. That optimisation is exactly Kadane's algorithm, and recognising "only the previous state matters" is a pattern you'll reuse in many DP problems.

Complexity#

ApproachTimeSpace
Brute forceO(n²)O(1)
Divide and conquerO(n log n)O(log n)
Kadane'sO(n)O(1)

Variation 1: maximum product subarray#

With multiplication, a negative number can turn the smallest product into the largest. Track both the max and min ending here:

Python
def max_product(nums):
    cur_max = cur_min = best = nums[0]
    for x in nums[1:]:
        if x < 0:
            cur_max, cur_min = cur_min, cur_max   # a negative flips them
        cur_max = max(x, cur_max * x)
        cur_min = min(x, cur_min * x)
        best = max(best, cur_max)
    return best

print(max_product([2, 3, -2, 4]))     # 6
print(max_product([-2, 3, -4]))       # 24

Variation 2: maximum circular subarray#

If the array wraps around, the best subarray is either a normal one (Kadane) or one that wraps, which equals total − (minimum subarray):

Python
def max_subarray_circular(nums):
    total = sum(nums)
    cur_max = best_max = cur_min = best_min = nums[0]
    for x in nums[1:]:
        cur_max = max(x, cur_max + x)
        best_max = max(best_max, cur_max)
        cur_min = min(x, cur_min + x)
        best_min = min(best_min, cur_min)
    if best_max < 0:
        return best_max                 # all negative: wrapping would mean an empty subarray
    return max(best_max, total - best_min)

print(max_subarray_circular([5, -3, 5]))   # 10 (5 + 5, wrapping)

Variation 3: best time to buy and sell stock#

Maximum profit from one buy and one sell is Kadane's algorithm on the daily price differences:

Python
def max_profit(prices):
    best = current = 0
    for i in range(1, len(prices)):
        current = max(0, current + prices[i] - prices[i - 1])
        best = max(best, current)
    return best

print(max_profit([7, 1, 5, 3, 6, 4]))   # 5 (buy at 1, sell at 6)

Here an empty choice (no trade, profit 0) is allowed, so the reset-to-0 version is correct.

Kadane vs sliding window

Both scan contiguous ranges, but the sliding window technique needs a condition that only gets "worse" as the window grows. Kadane's works with negative numbers because it decides at each step whether the past helps or hurts.

Practice problems#

  • Maximum Subarray (LeetCode 53)
  • Maximum Product Subarray (152)
  • Maximum Sum Circular Subarray (918)
  • Best Time to Buy and Sell Stock (121)
  • Maximum Absolute Sum of Any Subarray (1749)
  • Max Sum of Rectangle No Larger Than K (363), applying Kadane's to 2D

Review complexity analysis in Big O notation explained.

Key takeaways#

  • At each index, either extend the previous subarray or start fresh: current = max(x, current + x).
  • Kadane's algorithm runs in O(n) time and O(1) space.
  • Initialise with nums[0] so all-negative arrays return the largest element.
  • It's dynamic programming where only the previous state is needed.
  • Track both max and min for products, and use total − min subarray for circular arrays.