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 check sublist sum is strictly greater than the total sum of given list Python
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, 4] is 7 which is strictly larger.
Algorithm Approach
To solve this, we will follow these steps −
Calculate total sum of all elements in the list
Use prefix sum approach from left to right
If any prefix sum becomes negative, the remaining sublist sum will be greater than total
Use suffix sum approach from right to left
If any suffix sum becomes negative, the remaining sublist sum will be greater than total
Return False if no such sublist is found
Example
class Solution:
def solve(self, nums):
total = sum(nums)
s = 0
# Check prefix sums from left to right
for i in nums:
s += i
if s < 0:
return True
s = 0
i = len(nums) - 1
# Check suffix sums from right to left
while i > -1:
s += nums[i]
if s < 0:
return True
i = i - 1
return False
# Test the solution
ob1 = Solution()
nums = [2, -4, 3, 5]
print(ob1.solve(nums))
The output of the above code is ?
True
How It Works
The algorithm works by checking if we can find a contiguous sublist whose sum is greater than the total sum. This happens when the remaining elements (after removing the sublist) have a negative sum.
For the example [2, −4, 3, 5] with total sum = 6 ?
Prefix sums: 2, −2 (negative found, so remaining [3, 5] has sum 8 > 6)
This means sublist [3, 5] with sum 8 is greater than total sum 6
Alternative Simple Approach
def has_greater_sublist(nums):
total_sum = sum(nums)
n = len(nums)
# Check all possible sublists
for i in range(n):
current_sum = 0
for j in range(i, n):
current_sum += nums[j]
if current_sum > total_sum:
return True
return False
# Test with examples
nums1 = [1, -2, 3, 4]
nums2 = [2, -4, 3, 5]
nums3 = [1, 2, 3]
print(f"nums1: {has_greater_sublist(nums1)}")
print(f"nums2: {has_greater_sublist(nums2)}")
print(f"nums3: {has_greater_sublist(nums3)}")
nums1: True nums2: True nums3: False
Conclusion
The optimized solution uses prefix and suffix sum checks to efficiently determine if any sublist sum exceeds the total sum. The key insight is that if any prefix or suffix sum becomes negative, the remaining elements form a sublist with sum greater than the total.
