- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- 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
Advertisements