Program to find the maximum sum of circular sublist in Python

PythonServer Side ProgrammingProgramming

Suppose we have a list of numbers nums, now consider a circular list of nums where the start and end of nums are neighbors. We have to find the maximum sum of a non-empty sublist in the circular list.

So, if the input is like nums = [2, 3, -7, 4, 5], then the output will be 14, as we can take the sub list [4, 5, 2, 3] which sums to 14.

To solve this, we will follow these steps −

  • max_sum := negative infinity, cur_max := 0

  • min_sum := positive infinity, cur_min := 0

  • for each num in nums, do

    • cur_max := maximum of num and cur_max + num

    • max_sum := maximum of max_sum and cur_max

    • cur_min := minimum of num and cur_min + num

    • min_sum := minimum of min_sum and cur_min

  • if max_sum <= 0, then

    • return max_sum

  • return maximum of max_sum and (sum of all elements in nums - min_sum)

Let us see the following implementation to get better understanding −

Example

import math
class Solution:
   def solve(self, nums):
      max_sum = -math.inf
      cur_max = 0
      min_sum = math.inf
      cur_min = 0
      for num in nums:
         cur_max = max(num, cur_max + num)
         max_sum = max(max_sum, cur_max)
         cur_min = min(num, cur_min + num)
         min_sum = min(min_sum, cur_min)
      if max_sum <= 0:
         return max_sum
      return max(max_sum, sum(nums) - min_sum)
ob = Solution()
nums = [2, 3, -7, 4, 5]
print(ob.solve(nums))

Input

[2, 3, -7, 4, 5]

Output

14
raja
Published on 09-Oct-2020 18:30:24
Advertisements