Kadane’s algorithm solves the maximum sum subarray problem, which involves finding a contiguous subarray with the largest sum within a one-dimensional array. It can be solved in time and space.
Formally, the problem is to find indices and with such that
is maximized. For example, for the array of values , the contiguous subarray with the largest sum is , with sum .
If we operate on the assumption that no empty subarrays are permitted, then the problem can be solved with the following code:
def max_subarray(numbers):
best_sum = float('-inf')
current_sum = 0
for x in numbers:
current_sum = max(x, current_sum + x)
best_sum = max(best_sum, current_sum)
return best_sum
If we allow for empty subarrays, we can make two changes to our code that allow us to default to an empty subarray:
- Initialize
best_sumto0 - Set
current_sumin the loop tomax(0, current_sum + x)
The runtime complexity is and the space complexity is .