This is a maximum sum contiguous problem from interviewbit.com
Problem : Find the contiguous subarray within an array (containing at least one number) which has the largest sum.
For example: Given the array [-2,1,-3,4,-1,2,1,-5,4], the contiguous subarray [4,-1,2,1] has the largest sum = 6.
This is my solution :
def max_sub_array(array):
""" Finds msub-array with maximum sum and returns the maximum sum and sub-array"""
max_start, max_stop = 0, 1 # Start, Stop of maximum sub-array
curr = 0 # pointer to current array
max_sum = array[0] # Sum of maximum array
current_sum = 0 # sum of current array
for i, elem in enumerate(array):
current_sum += elem
if max_sum < current_sum:
max_sum = current_sum
max_start = curr
max_stop = i + 1
if current_sum < 0:
current_sum = 0
curr = i + 1
return max_sum , array[max_start:max_stop]
checking test cases:
assert max_sub_array([-4,-2,-3,-4,-5]) == (-2,[-2]), "Wrong evaluation"
assert max_sub_array([-1]) == (-1,[-1]), "Wrong evaluation"
assert max_sub_array([-5, 1, -3, 7, -1, 2, 1, -4, 6]) == (11,[7, -1, 2, 1, -4, 6]), "Wrong evaluation"
assert max_sub_array([-5, 1, -3, 7, -1, 2, 1, -6, 5]) == (9, [7, -1, 2, 1]), "Wrong evaluation"
assert max_sub_array( [6, -3, -2, 7, -5, 2, 1, -7, 6]) == (8,[6, -3, -2, 7]), "Wrong evaluation"
assert max_sub_array([-5, -2, -1, -4, -7]) == (-1,[-1]), "Wrong evaluation"
assert max_sub_array( [4, 1, 1, 4, -4, 10, -4, 10, 3, -3, -9, -8, 2, -6, -6, -5, -1, -7, 7, 8]) == (25,[4, 1, 1, 4, -4, 10, -4, 10, 3]), "Wrong evaluation"
assert max_sub_array([4, -5, -1, 0, -2, 20, -4, -3, -2, 8, -1, 10, -1, -1 ]) == (28, [20, -4, -3, -2, 8, -1, 10]), "Wrong evaluation"
How can this code be optimised ?