This version of Kadane's algorithm, named for Joseph Born Kadane, permits the empty subsequence. For , let be the maximum of zero and the weight of a contiguous subsequence ending exactly at position . Let be the best weight anywhere in the first positions. UseA segment ending at either extends one ending at or starts at ; the zero candidate permits discarding a negative predecessor and the empty answer. Any best segment of the first positions either ends at or already occurs in the first . These two decompositions prove the dynamic programming equations by induction.
Here is an implementation returning endpoints, using zero-based indexing:There is exactly one addition per input element, hence additions and comparisons. Auxiliary storage is . The all-negative case retains interval and weight zero. The example returns and weight 8, hence the desired contiguous subsequence.
best_segment(a):
end_weight = best_weight = 0
start = best_lo = best_hi = 0
for j in range(len(a)):
trial = end_weight + a[j]
if trial <= 0:
end_weight = 0
start = j+1
else:
end_weight = trial
if end_weight > best_weight:
best_weight = end_weight
best_lo, best_hi = start, j+1
return (best_lo, best_hi, best_weight) Articles by others on the same topic
There are currently no matching articles.