Maximum subarray is pretty well known problem with a simple algorithm to solve in O(n)
. Directly from the link above:
def max_subarray(A):
max_ending_here = max_so_far = A[0]
for x in A[1:]:
max_ending_here = max(x, max_ending_here + x)
max_so_far = max(max_so_far, max_ending_here)
return max_so_far
The problem mentions at least one positive integer, so this is equivalent to the above:
def max_subarray(A):
max_ending_here = max_so_far = 0
for x in A:
max_ending_here = max(x, max_ending_here + x)
max_so_far = max(max_so_far, max_ending_here)
return max_so_far
This is pretty simple to extend to a maximum window size k
:
def max_subarray(A, k):
max_ending_here = max_so_far = sliding_indexwindow = 0
for i, x in enumerate(A):
if sliding_indexwindow == k:
max_ending_here, -window = max((last_x, 1), (max_ending_here-A[i-k]
sliding_index, window-= 1))
max_ending_here, sliding_indexwindow = max((x, 1), (max_ending_here+x, sliding_index+1window+1))
last_x, max_so_far = x, max(max_so_far, max_ending_here)
return max_so_far
Example:
In []: max_subarray([41, 90, -62, -16, 25, -61, -33, -32, -33], 5)
Out[]: 131
In []: max_subarray([-200, 91, 82, 43], 3)
Out[]: 216