-
Notifications
You must be signed in to change notification settings - Fork 0
/
largest continious sequence with zero sum.txt
67 lines (44 loc) · 1.25 KB
/
largest continious sequence with zero sum.txt
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
Largest Continuous Sequence Zero Sum
Problem Description
Given an array A of N integers.
Find the largest continuous sequence in a array which sums to zero.
Problem Constraints
1 <= N <= 106
-107 <= A[i] <= 107
Input Format
Single argument which is an integer array A.
Output Format
Return an array denoting the longest continuous sequence with total sum of zero.
NOTE : If there are multiple correct answers, return the sequence which occurs first in the array.
Example Input
A = [1,2,-2,4,-4]
Example Output
[2,-2,4,-4]
Example Explanation
[2,-2,4,-4] is the longest sequence with total sum of zero.
vector<int> Solution::lszero(vector<int> &A) {
int n=A.size();
int prefix=0;
unordered_map<int,int> mp;
mp.insert({0,-1});
pair<int,int> index={-1,-1};
int len=0;
for(int i=0;i<n;i++){
prefix +=A[i];
if(mp.find(prefix)!=mp.end()){
if(len<i-mp[prefix]){
len=i-mp[prefix];
index.first=mp[prefix];
index.second=i;
}
}
else{
mp.insert({prefix,i});
}
}
if(index.second!=-1){
vector<int> ans(A.begin()+index.first+1,A.begin()+index.second+1);
return ans;
}
return {};
}