- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Program to find length of longest sublist whose sum is 0 in Python
Suppose we have a list with only two values 1 and −1. We have to find the length of the longest sublist whose sum is 0.
So, if the input is like nums = [1, 1, −1, 1, 1, −1, 1, −1, 1, −1], then the output will be 8, as the longest sublist is [−1, 1, 1, −1, 1, −1, 1, −1] whose sum is 0.
To solve this, we will follow these steps −
table := a new empty map
cs := 0, max_diff := 0
for i in range 0 to size of nums − 1, do
cs := cs + nums[i]
if cs is same as 0, then
max_diff := maximum of i + 1 and max_diff
if cs is in table, then
max_diff := maximum of max_diff and (i − table[cs])
otherwise,
table[cs] := i
return max_diff
Let us see the following implementation to get better understanding −
Example
class Solution: def solve(self, nums): table = {} cs = 0 max_diff = 0 for i in range(len(nums)): cs += nums[i] if cs == 0: max_diff = max(i + 1, max_diff) if cs in table: max_diff = max(max_diff, i − table[cs]) else: table[cs] = i return max_diff ob = Solution() nums = [1, 1, −1, 1, 1, −1, 1, −1, 1, −1] print(ob.solve(nums))
Input
[1, 1, −1, 1, 1, −1, 1, −1, 1, −1]
Output
8
- Related Articles
- Program to find length of longest distinct sublist in Python
- Program to find length of longest alternating inequality elements sublist in Python
- Program to find length of longest sublist with given condition in Python
- Program to find length of longest strictly increasing then decreasing sublist in Python
- Program to find length of longest consecutive sublist with unique elements in Python
- Program to find length of longest sublist with value range condition in Python
- Program to find length of longest contiguously strictly increasing sublist after removal in Python
- Program to find length of longest contiguous sublist with same first letter words in Python
- Program to find length of longest sublist containing repeated numbers by k operations in Python
- Program to find size of smallest sublist whose sum at least target in Python
- Program to find length of longest path with even sum in Python
- Program to find length of longest sublist where difference between min and max smaller than k in Python
- Program to find longest equivalent sublist after K increments in Python
- Program to find sum of contiguous sublist with maximum sum in Python
- Program to find length of contiguous strictly increasing sublist in Python

Advertisements