
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
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 Articles
- 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 – Adjacent elements in List
- Program to find maximum sum of popped k elements from a list of stacks in Python
- Program to find minimum possible difference of indices of adjacent elements in Python
- Python program to find largest number in a list
- Python program to find Cumulative sum of a list
- Program to find the sum of largest K sublist in Python
- Program to find largest sum of any path of a binary tree in Python
- Program to find sum of unique elements in Python

Advertisements