- Related Questions & Answers
- Program to find sum of non-adjacent elements in a circular list in python
- Program to find maximum sum of non-adjacent nodes of a tree in Python
- Program to find largest sum of 3 non-overlapping sublists of same sum in Python
- Python program to find sum of elements in list
- Find sum of elements in list in Python program
- Python program to find N largest elements from a list
- Python program to find Cumulative sum of a list
- Program to find minimum possible difference of indices of adjacent elements in Python
- Program to find maximum sum of popped k elements from a list of stacks in Python
- Program to find largest sum of any path of a binary tree in Python
- Program to find sum of all elements of a tree in Python
- Program to find the sum of largest K sublist in Python
- Python program to find largest number in a list
- Maximum sum of difference of adjacent elements in C++
- Program to find the largest product of two distinct elements in Python

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

Suppose we have a list of numbers called nums, we will define a function that returns the largest sum of non-adjacent numbers. Here the numbers can be 0 or negative.

So, if the input is like [3, 5, 7, 3, 6], then the output will be 16, as we can take 3, 7, and 6 to get 16.

To solve this, we will follow these steps−

if size of nums <= 2, then

return maximum of nums

noTake := 0

take := nums[0]

for i in range 1 to size of nums, do

take := noTake + nums[i]

noTake := maximum of noTake and take

return maximum of noTake and take

Let us see the following implementation to get better understanding −

class Solution: def solve(self, nums): if len(nums) <= 2: return max(nums) noTake = 0 take = nums[0] for i in range(1, len(nums)): take, noTake = noTake + nums[i], max(noTake, take) return max(noTake, take) ob = Solution() nums = [3, 5, 7, 3, 6] print(ob.solve(nums))

[3, 5, 7, 3, 6]

16

Advertisements