I am trying to solve the generative recursion problem in Python. The question arises:
- In the list, which consists of integers, find the neighboring sub-list that has the largest amount and return this amount.
- For example, if the given list is [-2, 1, -3, 4, -1, 2, 1, -5, 4], then the neighboring subset that has the largest sum is [4, -1, 2, 1] which has a sum of 6
I have to follow this algorithm to solve find_max:
- Divide this list (at the midpoint) into two: L_left and L_right.
- Returns the maximum value of the following 3:
- The maximum amount of any subscriptions is completely in L_left (using the find_max recursive call).
- The maximum amount of any subscriptions is entirely in L_right (using the find_max recursive call).
- The maximum subselect that overlaps L_left and L_right; those.
- First: find the maximum amount of any sublist, starting from the middle (left) and ending at some point to the left of the midpoint.
- Second: find the maximum amount of any sublist, starting from the middle (towards the right) and ending at some point to the right of the middle.
- Finally: add the two maximum amounts.
I 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 can be solved for lists of length 2. How can I expand this to work for a list with a large number of elements?
user2541757
source share