Skip to main content
Beginnercoding Verified

Find the maximum sum of a contiguous subarray (Kadane's algorithm).

ReportedSource: GeeksforGeeks interview experience: Microsoft SDE

Quick answer

Kadane: cur = max(x, cur + x), best = max(best, cur). Initialise with the first element so all-negative arrays work. O(n), O(1).

Constraints

  • Input: first line n, second line n integers (0 <= n <= 100000, |value| <= 10^4).
  • Output: the maximum sum of a non-empty contiguous subarray. If n is 0, print 0.

Sample I/O

in: 9 -2 1 -3 4 -1 2 1 -5 4

out: 6

in: 1 5

out: 5

in: 3 -3 -1 -2

out: -1

Loading editor…
Output

Sign up to run your code in the sandbox.

Sign up to run code and get an AI review

You can read and edit the challenge freely — running it in the sandbox and getting AI feedback need a free account.

Sign up free

Hints

Reference solution

Kadane's algorithm. Walk the array keeping cur, the best sum of a subarray ending at the current index. Either extend the previous subarray or start fresh at this element, whichever is larger.

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

Why it works. If the running sum ever becomes negative, it can only reduce any future subarray, so dropping it is optimal.

Complexity. O(n) time, O(1) space.

Edge cases. All negative numbers: initialising with nums[0] (not 0) returns the largest single element.

Follow-ups. Return the indices (record the start when you reset cur); maximum circular subarray (max of Kadane and total minus minimum subarray); divide and conquer O(n log n) version.

Discussion