- Related Questions & Answers
- Program to find largest sum of non-adjacent elements of a list in Python
- Program to find maximum sum of non-adjacent nodes of a tree in Python
- Python program to find sum of elements in list
- Find sum of elements in list in Python program
- Program to find the maximum sum of circular sublist 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 sum of all elements of a tree in Python
- Maximum sum in circular array such that no two elements are adjacent in C++
- Program to find largest sum of 3 non-overlapping sublists of same sum in Python
- Program to find maximum sum of two non-overlapping sublists in Python
- Find sum of frequency of given elements in the list in Python
- Maximum sum of difference of adjacent elements in C++
- Sum of the nodes of a Circular Linked List in C++

- 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 that is representing a circular list. We have to find the largest sum of non-adjacent numbers.

So, if the input is like nums = [10, 3, 4, 8], then the output will be 14, as we can take 10 and 4. We cannot take 10 and 8 as they are adjacent.

To solve this, we will follow these steps −

- n := size of nums
- nums1 := nums[from index 0 to n - 2]
- nums2 := nums[from index 1 to end]
- Define a function f() . This will take i
- if i >= size of nums1 , then
- return 0

- return maximum of nums1[i] + f(i + 2) and f(i + 1)
- Define a function g() . This will take j
- if j >= size of nums2 , then
- return 0

- return maximum of nums2[j] + g(j + 2) and g(j + 1)
- From the main method do the following −
- return maximum of f(0) and g(0)

Let us see the following implementation to get better understanding −

class Solution: def solve(self, nums): n = len(nums) nums1 = nums[: n - 1] nums2 = nums[1:] def f(i): if i >= len(nums1): return 0 return max(nums1[i] + f(i + 2), f(i + 1)) def g(j): if j >= len(nums2): return 0 return max(nums2[j] + g(j + 2), g(j + 1)) return max(f(0), g(0)) ob = Solution() nums = [10, 3, 4, 8] print(ob.solve(nums))

[10, 3, 4, 8]

14

Advertisements