Program to check sublist sum is strictly greater than the total sum of given list Python

PythonServer Side ProgrammingProgramming

Suppose we have a list of numbers called nums, we have to check whether there is a sublist such that its sum is strictly greater than the total sum of the list.

So, if the input is like nums = [1, −2, 3, 4], then the output will be True, as the sum of the list is 6 and the sum of the sublist [3, 5] is 8 which is strictly larger.

To solve this, we will follow these steps −

  • total := sum of elements nums

  • s := 0

  • for each i in nums, do

    • s := s + i

    • if s < 0, then

      • return True

  • s := 0

  • i := size of nums − 1

  • while i > −1, do

    • s := s + nums[i]

    • if s < 0, then

      • return True

    • i := i − 1

  • return False

Let us see the following implementation to get better understanding −

Example

 Live Demo

class Solution:
   def solve(self, nums):
      total = sum(nums)
      s = 0
      for i in nums:
         s += i
         if s < 0:
            return True
      s = 0
      i = len(nums) − 1
      while i > −1:
         s += nums[i]
         if s < 0:
            return True
         i = i − 1
      return False

ob1 = Solution()
nums = [2, -4, 3, 5]
print(ob1.solve(nums))

Input

[2, −4, 3, 5]

Output

True
raja
Published on 21-Oct-2020 11:15:05
Advertisements