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 −
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]