The standard way to find the maximum subarray is Kadene's algorithm. If the input is a large numpy array, is there anything faster than the native python implementation?
import timeit
setup = '''
import random
import numpy as np
def max_subarray(A):
max_so_far = max_ending_here = 0
for x in A:
max_ending_here = max(0, max_ending_here + x)
max_so_far = max(max_so_far, max_ending_here)
return max_so_far
B = np.random.randint(-100,100,size=100000)
'''
print min(timeit.Timer('max_subarray(B)',setup=setup).repeat(5, 100))
Little test with Cython in an iPython notebook (because of that no timeit, doesn't appear to work with the
%%cython
environment :)Original version:
Cython version:
Results:
Definitely a notable increase without too much effort :)