I am trying to solve a generative recursion problem in Python. The question is:
- In a list that consists of integers, find the adjoining sublist which has the largest sum and return that sum.
- For example, if the given list is [−2, 1, −3, 4, −1, 2, 1, −5, 4], the adjoining sublist which has the largest sum is [4, −1, 2, 1], which has a sum 6
I have to follow the given algorithm to solve find_max:
- Split given list (at the midpoint) into two: L_left and L_right.
- Return the maximum value of following 3:
- The maximum sum of any sublist resides entirely in L_left (using a recursive call to find_max).
- The maximum sum of any sublist resides entirely in L_right (using a recursive call to find_max).
- The maximum sublist that overlaps L_left and L_right; i.e.,
- First: Find max sum of any sublist starting from the midpoint (towards the left) and ending at some point on the left of the midpoint
- Second: Find the max sum of any sublist starting from the midpoint (towards the right) and ending at some point on the right of the midpoint
- Finally: Add the two max sums.
I have tried the following:
def find_max(L):
length = len(L)
mid_index = length/2
if length == 1:
return L[0]
else:
left = find_max(L[0:(length/2)])
right = find_max(L[(length/2):length])
max_subset = max(left,right,left+right)
return max_subset
This is able to solve for lists with length 2. How do I extend this to work for a list with more elements?
[1, 2, -1, 4]and an adjoining sublist of[−5, 1, 4, −2, 2, −1, 2, −3, 1, −3, 4]. As I understanding the adjoining sublist with the maximum value would be[1, 4, -2, 2, -1, 2]with a sum of 6. - Lennart Regebro[1, 2, -1, 4]is not a sublist of[−5, 1, 4, −2, 2, −1, 2, −3, 1, −3, 4]. Is there a typo? - zneak