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.
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.
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.