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