-
Notifications
You must be signed in to change notification settings - Fork 86
/
Copy pathLengthOfLargestSubarrayWithZeroSum.java
50 lines (39 loc) · 1.31 KB
/
LengthOfLargestSubarrayWithZeroSum.java
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
42
43
44
45
46
47
48
49
50
// Java program for the above approach
import java.util.HashMap;
class LengthOfLargestSubarrayWithZeroSum {
// Returns length of the maximum length
// subarray with 0 sum
static int maxLen(int arr[])
{
// Creates an empty hashMap hM
HashMap<Integer, Integer> hM
= new HashMap<Integer, Integer>();
int sum = 0; // Initialize sum of elements
int max_len = 0; // Initialize result
// Traverse through the given array
for (int i = 0; i < arr.length; i++) {
// Add current element to sum
sum += arr[i];
if (sum == 0)
max_len = i + 1;
// Look this sum in hash table
Integer prev_i = hM.get(sum);
// If this sum is seen before, then update
// max_len if required
if (prev_i != null)
max_len = Math.max(max_len, i - prev_i);
else // Else put this sum in hash table
hM.put(sum, i);
}
return max_len;
}
// Drive's code
public static void main(String arg[])
{
int arr[] = { 15, -2, 2, -8, 1, 7, 10, 23 };
// Function call
System.out.println(
"Length of the longest 0 sum subarray is "
+ maxLen(arr));
}
}