Repaso
EspaƱol
Algorithms & DSAdvancedALG-27

Maximum subarray sum in O(n)?

Options

  1. Kadane's algorithm (Correct option)
  2. Floyd-Warshall
  3. Binary search
  4. Merge sort

Answer

Kadane's algorithm

Why

Kadane's idea: walk through the array keeping cur, the best sum of a subarray that ends at the current position.

At each number x, either extend the previous subarray (cur + x) or start fresh at x, whichever is bigger. Track the best cur ever seen.

One pass, O(n) time, O(1) memory.

def max_subarray(nums):
    best = cur = nums[0]
    for x in nums[1:]:
        cur = max(x, cur + x)
        best = max(best, cur)
    return best

Remember

Kadane: extend or restart at each element.

Key terms

Practice this question in Repaso