Maximum sum combination from two list in Python
We have given the two lists from the user. Our task is to find the Maximum Sum combination from the given two list in Python.
But we need to keep it in the mind that choose elements from both the lists such that:-
No two elements have the same index.
No two consecutive elements can be selected from a single list.
Here is the code of the problem
def find(l1,l2,n): trail=[[0 for i in range(2)] for j in range(n)] for i in range(n): if(i == 0): trail[i] = l1[i] trail[i] = l2[i] continue else: trail[i] = max(trail[i - 1],trail[i - 1] + l1[i]) trail[i] = max(trail[i - 1],trail[i - 1] + l2[i]) return max(trail[n - 1],trail[n - 1]) #main driver l1=list(map(int,input().split())) l2=list(map(int,input().split())) n=len(l1) print(find(l1,l2,n))
We made a function name find to find all the maximum sum.
I use this approach because of the time complexity of this is O(n).
In the find function, we take a list trail which will store (0,0) up to n times, ‘n’ is the length of the list l1.
Now in the loop for the zeroth index of the trail, we inserted the first element of both the list.
For others, we use a function max which will select the maximum of the parameters given in it.
In max we passed trail[i – 1],trail[i – 1] + l1[i] for the i>0
This will check onne by one for all the lemenets presents in the both the lists.
In the end, we have returned the maximum element from the last pair of the trail list.
Now we used a map function that is used to take multiple inp[uts at a time.
by using map function we accept input from the user.
Then pass the two lists with the length of any one of the list generally the list with a smaller length.
Because if we pass the length of the larger list it will show the error that list index is out of range.
By Shrimad Mishra
Here is the output:-