
- Python 3 Basic Tutorial
- Python 3 - Home
- What is New in Python 3
- Python 3 - Overview
- Python 3 - Environment Setup
- Python 3 - Basic Syntax
- Python 3 - Variable Types
- Python 3 - Basic Operators
- Python 3 - Decision Making
- Python 3 - Loops
- Python 3 - Numbers
- Python 3 - Strings
- Python 3 - Lists
- Python 3 - Tuples
- Python 3 - Dictionary
- Python 3 - Date & Time
- Python 3 - Functions
- Python 3 - Modules
- Python 3 - Files I/O
- Python 3 - Exceptions
Program to find sum of non-adjacent elements in a circular list in python
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 −
Example
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))
Input
[10, 3, 4, 8]
Output
14
- Related Articles
- 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
- Python – Adjacent elements in List
- Program to find sum of odd elements from list in Python
- Program to find the maximum sum of circular sublist in Python
- Program to find maximum sum of popped k elements from a list of stacks in Python
- Python program to remove duplicate elements from a Circular Linked List
- Python program to sort the elements of the Circular Linked List
- Program to find minimum possible difference of indices of adjacent elements in Python
- Program to find sum of unique elements in Python
- Maximum sum in circular array such that no two elements are adjacent in C++
- Program to find sum of all elements of a tree in Python
- Python program to find Cumulative sum of a list

Advertisements