-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathDay55.java
More file actions
41 lines (35 loc) · 1.14 KB
/
Day55.java
File metadata and controls
41 lines (35 loc) · 1.14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import java.util.*;
public class Day55 {
public static int longestSubarrayWithZeroSum(int[] nums) {
int maxLength = 0;
int sum = 0;
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
sum += nums[i];
if (sum == 0) {
maxLength = i + 1;
} else {
if (map.containsKey(sum)) {
maxLength = Math.max(maxLength, i - map.get(sum));
} else {
map.put(sum, i);
}
}
}
return maxLength;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int T = scanner.nextInt();
for (int t = 0; t < T; t++) {
int N = scanner.nextInt();
int[] nums = new int[N];
for (int i = 0; i < N; i++) {
nums[i] = scanner.nextInt();
}
int result = longestSubarrayWithZeroSum(nums);
System.out.println(result);
}
scanner.close();
}
}