#C2613. Longest Zero Sum Subarray
Longest Zero Sum Subarray
Longest Zero Sum Subarray
Problem Description
You are given T test cases. Each test case begins with an integer N which denotes the number of elements in an array, followed by N integers. For each test case, your task is to find the length of the longest contiguous subarray whose sum is zero. If no such subarray exists, output -1
.
The problem can be described mathematically as: find the maximum value of l such that there exists an index i with \[ \sum_{j=i}^{i+l-1} a_j = 0 \] where \(a_j\) represents the jth element of the array. If no subarray sums to zero, return -1.
Note: The entire subarray is considered, and the elements are consecutive.
inputFormat
Input Format
The first line of the input contains an integer T
representing the number of test cases. Each test case is described as follows:
- The first line contains an integer
N
— the number of elements in the array. - The second line contains
N
space-separated integers representing the elements of the array.
All input is read from stdin
.
outputFormat
Output Format
For each test case, output a single line containing one integer — the length of the longest contiguous subarray with a sum of zero. If no such subarray exists, output -1
.
All output should be written to stdout
.
3
5
1 -1 3 2 -2
4
1 2 3 4
6
1 -1 2 -2 3 -3
2
-1
6
</p>