Program to find largest sum of non-adjacent elements of a list in Python

PythonServer Side ProgrammingProgramming

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

 Live Demo

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
raja
Published on 09-Oct-2020 18:48:03
Advertisements