- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

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

# Program to find largest sum of non-adjacent elements of a list in Python

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 −

## Example

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))

## Input

[3, 5, 7, 3, 6]

## Output

16

- 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
- Program to find sum of odd elements from list in Python
- 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 the sum of largest K sublist in Python
- Program to find sum of all elements of a tree in Python
- Program to find sum of unique elements in Python
- Python program to find largest number in a list

Advertisements