Skip to contentKEEP THE CRAFTTHE SANCTUARY

Kadane's Algorithm

Track the best nonempty contiguous sum ending at the current index, then the best over all processed endings. Preserve negative answers, restart boundaries and a specified tie policy.

1 practice exercise1 interview problem

Recognize it when The objective is a maximum-sum contiguous subarray with unrestricted length.

Checking your account…

Kadane's Algorithm Code Labs

Choose Extend or Restart

For each position, the best subarray ending there either extends the previous ending subarray or restarts at the current value. No other contiguous candidate can end at that index.

Track Ending Here and Best So Far

Ending-here answers a constrained state; best-so-far summarizes all endings processed. Update ending first, then compare it with the global best.

Trace Kadane States

Reference
def kadane_trace(values):
    ending=best=values[0];trace=[[ending,best]]
    for value in values[1:]:ending=max(value,ending+value);best=max(best,ending);trace.append([ending,best])
    return trace
Practice

Implement kadane_trace(values). Return [ending_here,best_so_far] after each value; values is nonempty.

Public tests

  • Choose extend or restart

Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor

Trace Kadane States

def kadane_trace(values):
    ending=best=values[0];trace=[[ending,best]]
    for value in values[1:]:ending=max(value,ending+value);best=max(best,ending);trace.append([ending,best])
    return trace

Restart Without Confusing Ending with Global Best

Predict both calls to the existing state Lab. The first has a local restart before a new global record; the second proves that zero is not a legal substitute for a nonempty negative answer.

Step Executed statement State Why
Initialize nonempty ending=best=values[0];trace=[[ending,best]] ending=4, best=4 The first element is a valid nonempty segment.
Extend through loss ending=max(value,ending+value);best=max(best,ending);trace.append([ending,best]) value=-6: ending=-2, best=4 The best endpoint-specific sum may fall while global best stays unchanged.
Restart at 3 ending=max(value,ending+value);best=max(best,ending);trace.append([ending,best]) ending=3, best=4 A standalone 3 beats extending -2 to 1, but not the earlier global 4.
Extend new segment ending=max(value,ending+value);best=max(best,ending);trace.append([ending,best]) value=2: ending=5, best=5 The new contiguous [3,2] beats every earlier ending.
All-negative call ending=max(value,ending+value);best=max(best,ending);trace.append([ending,best]) after -2: ending=-2, best=-2 A real negative value wins; no empty zero state is introduced.
Print Output
print(kadane_trace([4,-6,3,2])) [[4, 4], [-2, 4], [3, 4], [5, 5]]
print(kadane_trace([-4,-2])) [[-4, -4], [-2, -2]]

For max_subarray_range, strict comparisons preserve the earlier winning range on equal sums. The sum recurrence remains the same, but boundary state and tie semantics are part of the output contract.

Handle All Negative Arrays

Initialize from the first value rather than zero unless the empty subarray is explicitly allowed. Zero initialization incorrectly reports an empty result for all-negative input.

Recover Maximum Subarray Boundaries

Reference
def max_subarray_range(values):
    best_sum=ending=values[0];best_left=best_right=start=0
    for index in range(1,len(values)):
        if ending+values[index]<values[index]:ending=values[index];start=index
        else:ending+=values[index]
        if ending>best_sum:best_sum=ending;best_left=start;best_right=index
    return [best_sum,best_left,best_right]
Practice

Implement max_subarray_range(values). Return [sum,left,right] with inclusive bounds, preferring the earliest range on ties. values is nonempty.

Public tests

  • Track restart boundaries

Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor

Recover Maximum Subarray Boundaries

def max_subarray_range(values):
    best_sum=ending=values[0];best_left=best_right=start=0
    for index in range(1,len(values)):
        if ending+values[index]<values[index]:ending=values[index];start=index
        else:ending+=values[index]
        if ending>best_sum:best_sum=ending;best_left=start;best_right=index
    return [best_sum,best_left,best_right]

Recover Subarray Boundaries

When restart wins, set the candidate left boundary to the current index. When ending becomes the strict global best, copy both boundaries. Define tie policy before choosing strict or non-strict comparisons.

Explain It in an Interview

Say: “The best subarray ending here must either be the current item alone or the prior ending plus it. I keep the better and update the best over all endings.” State O(n) time, O(1) space, empty policy, and tie behavior.

Template To Memorize

Learn this shape by heart; most problems in this family change only one or two lines of it.

Kadane's best running sum

Extend or restart; keep the best.

You need the best contiguous subarray (largest sum, product, or profit).

Trigger words

  • maximum subarray
  • largest contiguous sum
  • maximum product subarray
  • buy once, sell once
  • max profit, one trade
def max_subarray(nums):
    best = nums[0]
    current = 0
    for num in nums:
        current = max(num, current + num)   # extend the run, or restart here
        best = max(best, current)
    return best

Spot it when

  • 'Maximum subarray'.
  • 'Best time to buy and sell a stock' (one transaction).

Remember

  • current is the best sum of a subarray that ends exactly here.
  • best starts from nums[0] so an all-negative array still works.

How problems bend it

  • Maximum product: Track both the largest and the smallest product ending here, because a negative number swaps them.
  • Best time to buy and sell: Track the lowest price so far and the best price - lowest.

Python Version Note

Python 3.11+

The code uses standard Python syntax and containers supported by the browser Judge. The Kadane's Algorithm proof does not depend on a minor Python release.

Verify in Python docs(opens in a new tab)

Complexity & Invariants

Interview bounds depend on the stated representation, input model, and real Python operations.

OperationAverageWorstInterview note
Maximum-sum scanO(n)O(n)One ending/global comparison per value.
Displayed state traceO(n)O(n)The Lab also creates values[1:] and stores one pair per value.

Space

O(1) state for the boundary Lab; O(n) returned trace and temporary slice for the state Lab.

Assumptions

  • Initializing from zero changes the contract to permit an empty segment.
  • The range Lab restarts only on a strictly better single value and replaces the saved best only on strict improvement.

Invariants Worth Saying Aloud

  1. ending is the best nonempty subarray sum ending exactly at this index.
  2. best is the maximum ending value seen in the processed prefix.
  3. A candidate start moves only when restarting wins under the chosen tie rule.

When To Use Or Avoid Kadane's Algorithm

Use It When

  • Use Kadane for a linear scan of nonempty maximum subarray sum.
  • Track a candidate start and copy global boundaries when the best strictly improves.

Choose Another Tool When

  • A subsequence can skip internal values and needs a different recurrence.
  • Length bounds, circular wrapping or maximum product introduce different state or preprocessing.

Common Pitfalls

These are the mistakes most likely to survive a happy-path example and fail a boundary case.

Allowing an empty winner on negative input

Starting best at 0 lets the empty subarray beat every real negative element.

Prevent it: Initialize the nonempty state from the first element.

Avoid

ending=best=0

Use instead

ending=best=values[0]

Updating the global best before the ending state

The new value can improve ending. Comparing best with the old ending misses that improvement.

Prevent it: Update ending before comparing it with best.

Avoid

best=max(best,ending)
ending=max(value,ending+value)

Use instead

ending=max(value,ending+value)
best=max(best,ending)

Keeping the old start after a restart

After negative ending=-3, a new value 5 is better alone. Leaving start=0 falsely includes earlier elements in its range.

Prevent it: Move start to the current index when the single value wins.

Avoid

ending=value

Use instead

ending=value
start=index

Reviewed References

Official Python documentation supports language behavior. Canonical problem pages provide additional practice context.