You are given a list of integers that may contain positive numbers, negative numbers, and zero.
A subarray is a contiguous part of the list.
Your task is to find the maximum length of any subarray whose sum is exactly 0.
If no non-empty subarray has sum equal to 0, return 0.
Method Signature
Longest Subarray
int longestZeroSumSubarray(List<Integer> numbers)
numbers is a list of integers.
- The list may contain positive integers, negative integers, and zero.
- The method returns the length of the longest contiguous subarray whose sum is exactly
0.
- If there is no non-empty subarray with sum
0, return 0.
Constraints
1 ≤ numbers.size() ≤ 100,000
-1000,000,000 ≤ numbers[i] ≤ 1000,000,000
- The answer must fit in a 32-bit signed integer.
- The sum of a subarray may exceed a 32-bit signed integer, so use a suitable larger integer type when needed.
Examples
Example 1
Method call: longestZeroSumSubarray(numbers = [15, -2, 2, -8, 1, 7, 10, 23])
Output: 5
Explanation: The subarray [-2, 2, -8, 1, 7] has sum 0 and length 5. No longer subarray has sum equal to 0.
Example 2
Method call: longestZeroSumSubarray(numbers = [1, 2, 3])
Output: 0
Explanation: There is no non-empty subarray whose sum is equal to 0.
Example 3
Method call: longestZeroSumSubarray(numbers = [1, -1, 3, 2, -2, -3, 4])
Output: 6
Explanation: The subarray [1, -1, 3, 2, -2, -3] has sum 0 and length 6.
Example 4
Method call: longestZeroSumSubarray(numbers = [0, 0, 5, -5, 2])
Output: 4
Explanation: The subarray [0, 0, 5, -5] has sum 0 and length 4.