Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to find sum of non-adjacent elements in a circular list in python
Suppose we have a list of numbers representing a circular list. We need to find the largest sum of non-adjacent elements, where the first and last elements are considered adjacent due to the circular nature.
For example, if the input is nums = [10, 3, 4, 8], the output will be 14 by selecting elements 10 and 4. We cannot select 10 and 8 because they are adjacent in the circular arrangement.
Algorithm Approach
Since the list is circular, we need to handle two cases separately:
- Case 1: Include the first element but exclude the last element
- Case 2: Exclude the first element but can include the last element
The solution involves:
- Create
nums1from index 0 to n-2 (excluding last element) - Create
nums2from index 1 to end (excluding first element) - Find maximum sum for both cases using recursion
- Return the maximum of both results
Implementation
class Solution:
def solve(self, nums):
n = len(nums)
# Handle edge cases
if n == 0:
return 0
if n == 1:
return nums[0]
if n == 2:
return max(nums[0], nums[1])
# Case 1: Include first element, exclude last
nums1 = nums[: n - 1]
# Case 2: Exclude first element, can include last
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))
# Test the solution
ob = Solution()
nums = [10, 3, 4, 8]
print("Input:", nums)
print("Output:", ob.solve(nums))
Input: [10, 3, 4, 8] Output: 14
How It Works
The algorithm works by breaking down the circular constraint:
- Function f(): Processes elements 0 to n-2, ensuring we don't select both first and last elements
- Function g(): Processes elements 1 to n-1, starting from the second element
- Each function recursively chooses between including the current element (and skipping the next) or skipping the current element
Additional Example
# Test with different inputs
ob = Solution()
test_cases = [
[2, 1, 4, 9],
[5, 1, 3, 9],
[1, 2, 3]
]
for nums in test_cases:
result = ob.solve(nums)
print(f"Input: {nums} ? Output: {result}")
Input: [2, 1, 4, 9] ? Output: 11 Input: [5, 1, 3, 9] ? Output: 12 Input: [1, 2, 3] ? Output: 3
Conclusion
This approach effectively handles the circular constraint by considering two separate linear cases. The recursive solution explores all possible combinations while respecting the non-adjacent requirement, ensuring we find the maximum sum.
