-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLongestSubSetWithZeroSum.cpp
More file actions
70 lines (60 loc) · 1.04 KB
/
Copy pathLongestSubSetWithZeroSum.cpp
File metadata and controls
70 lines (60 loc) · 1.04 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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#include<unordered_map>
using namespace std;
int length(int* arr,int size,int el)
{
int count=0;
for(int i=0;i<size;i++)
{
if(arr[i]==el)
{
count++;
}
}
bool flag=false;
int len=0;
for(int i=0;i<size;i++)
{
if(flag ==true)
{
len++;
}
if(arr[i]==el&&count>0)
{
flag=true;
count--;
}
if(arr[i]==el&&count==0)
{
flag=false;
}
}
return len;
}
int lengthOfLongestSubsetWithZeroSum(int* arr, int size){
// Write your code here
unordered_map<int,int>m;
if(size==1)
return 1;
int maxlen=0;
for(int i=1;i<size;i++)
{
arr[i]=arr[i]+arr[i-1];
}
for(int i=0;i<size;i++)
{
if(m[arr[i]]==0)
{
m[arr[i]]=1;
}
else
{
m[arr[i]]++;
int len=length(arr,size,arr[i]);
if(len>maxlen)
{
maxlen=len;
}
}
}
return maxlen;
}