-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHashmaps:Longest subset zero sum
More file actions
39 lines (35 loc) · 999 Bytes
/
Hashmaps:Longest subset zero sum
File metadata and controls
39 lines (35 loc) · 999 Bytes
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
import java.util.*;
/*
- You are given an integer array containing positive and negative numbers.
- Your task is to find out the length of the longest continuous subset of this array whose elements add upto zero.
*/
public class solution
{
public static int lengthOfLongestSubsetWithZeroSum(ArrayList<Integer> arr)
{
if(arr.size()==0)
return 0;
HashMap<Integer,Integer> h=new HashMap<>();
int sum=0;
int maxlength=0;
int maxlength1=0;
for(int i=0;i<arr.size();i++)
{
sum=sum+arr.get(i);
if(h.containsKey(sum)){
int k=h.get(sum);
int l=i-k;
maxlength1=l;}
// if(!h.containsKey(sum))
else
h.put(sum,i);
if(sum==0)
{
maxlength1=i+1;
}
if(maxlength1>maxlength)
maxlength=maxlength1;
}
return maxlength;
}
}