- Related Questions & Answers
- 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 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 contiguous strictly increasing sublist in Python
- Program to find sum of contiguous sublist with maximum sum in Python
- Program to find length of longest balanced subsequence in Python
- Program to find length of longest anagram subsequence in Python
- Program to find length of longest consecutive sequence in Python
- Program to find length of longest increasing subsequence in Python
- Program to find length of longest palindromic substring in Python
- Program to find length of longest possible stick in Python?
- Program to find length of longest palindromic subsequence in Python

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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 −

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))

[1, 1, −1, 1, 1, −1, 1, −1, 1, −1]

8

Advertisements