Since you tagged algorithm
here is an explanation followed by a python
implementation.
This problem is a straightforward extension of the Kadane's algorithm. Kadane's algorithm as follows:
for each item in arr:
current_max = max(current_max + item, item)
global_max = global_max(current_max, global_max)
We simply need to record the indices for whenever current and global max are updated:
for each item in arr:
# updating current max and keeping track current of start and end indices
current_max = max(current_max + item, item)
if item is new current_max: set current_start_index to this index
set current_end_index to this index
# keep track of global start and end indices
global_max = max(global_max, current_max)
if global_max has been updated:
set global_start to current_start
set global_end to current_end
Python implementation:
def maxSum(arr):
cur_max = glob_max = float('-inf')
glob_start = glob_end = cur_start = -1
for index, item in enumerate(arr):
if item > cur_max + item:
cur_max = item
cur_start = index
else:
cur_max += item
if cur_max > glob_max:
glob_max = cur_max
glob_start = cur_start
glob_end = index
return arr[glob_start:glob_end+1]
Some test cases:
arr = [-57, -10000, -1, -4, -45, -6, -9, -19, -16, -17]
arr = [-1, 2, -1, 20, -4, -5, -6, -9, -19, -16, -17]
Output:
[-1]
[2, -1, 20]
Note that if you want to consider the empty contiguous subarray just add a check at the end - if the global max is less than 0, return an empty array.
Finally some additional code to demonstrate that the algorithm is correct:
def kadane(arr):
a = b = float('-inf')
for i in arr:
a = max(i, a+i)
b = max(a, b)
return b
from random import random
for _ in range(10000):
arr = [random()-0.5 for _ in range(50)]
assert kadane(arr) == sum(maxSum(arr))
This creates random arrays with positive and negatives and asserts that the sum of the output array is equal to the output of the regular version of kadane's algorithm.
repl.it link with code