Coding Problem 6
Sum of non-adjacent
asked by Airbnb
Ques. Given a list of integers, write a function that returns the largest sum of non-adjacent number. Numbers can be 0 or negative.
For example - [2, 4, 6, 2, 5] should return 13 since we pick 2, 6 and 5. Another list [5, 1, 1, 5] should return 10 since we pick 5 and 5.
Solution.
In this problem we can not take the two contniuous inetgers means adjacents. Think about it like this if we have 1 element in the list we simply return it and if we have two elements then we can return the maximum number between them. Now for number of elements greater than 2 we have to skip the adjacent number. Suppose we have list of three integers so we can calculate the result by comparing the middle element and sum of first and last element. Now what we can do here is if we take out the last element from list then we will have only two remaining elements then we can then call the function recursively and in each function call one time we send the list without last element of current list and second time we call the function with last element plus first element only. In second call we skip the second element because it will be adjacent to third element. So each we call the functions recursively once without last element and then with last element by skipping the adjacent to last element.
So in base case we have a condition that if number of elements are less than or equal to 2 then we can return the simply maximum element from the list.
def max_sum(arr):
if not arr:
return 0
elif len(arr) <= 2:
return max(arr)
last_num = arr[-1]
with_last = max_sum(arr[:-2]) + last_num
without_last = max_sum(arr[:-1])
return max(with_last, without_last)
arr = [2, 4, 6, 2, 5]
print(max_sum(arr))
Output: 13

Comments
Post a Comment