Kadane Maximum Subarray Sum

Kadane's scan extends or restarts the running subarray at each item and records the best window, handling all-negative arrays correctly.

PythonData Integrity

Code

pythonsnippet
25 lines
def max_subarray(values):
    """Kadane's scan: extend or restart the run, tracking the maximum subarray sum."""
    best = running = values[0]
    start = best_start = end = 0
    for index in range(1, len(values)):
        # a fresh run beats extending only when the current sum went negative
        if running < 0:
            running = values[index]
            start = index
        else:
            running += values[index]
        if running > best:
            best = running
            best_start = start  # pin the best window's own start
            end = index
    return best, best_start, end

prices = [-2, 1, -3, 4, -1, 2, 1, -5, 4]
best, start, end = max_subarray(prices)
print("best sum:", best, "window:", prices[start:end + 1])

gaps = [5, -9, 6, -2, 3]
print("gap case:", max_subarray(gaps))

print("all negative:", max_subarray([-3, -1, -7]))

Output

Captured from a sandboxed run of this snippet in the build pipeline.

best sum: 6 window: [4, -1, 2, 1]
gap case: (7, 2, 4)
all negative: (-1, 1, 1)

How execution unfolds

A compact reading: the function max_subarray, doing all the work.

for index in range(1, len(values)) carries the work item by item.

What to watch for

  • All standard-library: copy it into a project and it just runs.

Using it

The signature in play: def max_subarray(values)

The run emits 3 labeled sections — best sum:, gap case:, all negative: — one per step.

Callers only need max_subarray — everything else stays internal.

Interactive Tools for This Topic

FAQ

What does the package manager see?
An empty dependency file. The snippet imports nothing that needs fetching. The file defines `max_subarray` at load time.