I created a recursive function that takes in an array of ints, and returns the sum of the continuous subarray with the largest sum.
Example:
input: 1 4 -9 8 1 3 3 1 -1 -4 -6 2 8 19 -10 -11
subarray: 8 1 3 3 1 -1 -4 -6 2 8 19
sum: 34
My algorithm is a little off. About 2/3's of my test inputs are wrong. A list of my tests is below the code.
def max_sum_subarray(arr, left, right):
maxLeftBorderSum = 0
maxRightBorderSum = 0
leftBorderSum = 0
rightBorderSum = 0
center = (left + right)/2
if left == right:
return arr[left]
maxLeftSum = min_sum_subarray(arr, left, center)
maxRightSum = min_sum_subarray(arr, center+1, right)
for i in range(center, left, -1):
leftBorderSum = leftBorderSum + arr[i]
if leftBorderSum > maxLeftBorderSum:
maxLeftBorderSum = leftBorderSum
for i in range(center+1, right):
rightBorderSum = rightBorderSum + arr[i]
if rightBorderSum > maxRightBorderSum:
maxRightBorderSum = rightBorderSum
return max(maxLeftBorderSum + maxRightBorderSum, max(maxRightSum, maxLeftSum))
Some tests:
1 4 -9 8 1 3 3 1 -1 -4 -6 2 8 19 -10 -11
Correct Answer = 34
My answer = 34
2 9 8 6 5 -11 9 -11 7 5 -1 -8 -3 7 -2
Correct Answer = 30
My answer = 28
10 -11 -1 -9 33 -45 23 24 -1 -7 -8 19
Correct Answer = 50
My answer = 47
31 -41 59 26 -53 58 97 -93 -23 84
Correct Answer = 187
My answer = 187
3 2 1 1 -8 1 1 2 3
Correct Answer = 7
My answer = 4
12 99 99 -99 -27 0 0 0 -3 10
Correct Answer = 210
My answer = 198
-2 1 -3 4 -1 2 1 -5 4
Correct Answer = 6
My answer = 6
#!python3
def max_sum_subarray(arr, left, right):
maxLeftBorderSum = 0
maxRightBorderSum = 0
leftBorderSum = 0
rightBorderSum = 0
center = (left + right)//2
if left == right:
if(arr[left]>0):return arr[left]
else:return 0
maxLeftSum = max_sum_subarray(arr, left, center)
maxRightSum = max_sum_subarray(arr, center+1, right)
for i in range(center, left-1, -1):
leftBorderSum = leftBorderSum + arr[i]
if leftBorderSum > maxLeftBorderSum:
maxLeftBorderSum = leftBorderSum
for i in range(center+1, right+1):
rightBorderSum = rightBorderSum + arr[i]
if rightBorderSum > maxRightBorderSum:
maxRightBorderSum = rightBorderSum
return max(maxLeftBorderSum + maxRightBorderSum,maxRightSum, maxLeftSum)