-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathLargestContZero.java
More file actions
63 lines (51 loc) · 1.47 KB
/
LargestContZero.java
File metadata and controls
63 lines (51 loc) · 1.47 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
package Hashing;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
/**
* Author - archit.s
* Date - 28/10/18
* Time - 2:48 PM
*/
public class LargestContZero {
public ArrayList<Integer> lszero(ArrayList<Integer> A) {
Map<Integer, Integer> map = new HashMap<>();
int leftIndex = -1, rightIndex = -1;
int sum = 0 ;
for(int i=0;i<A.size();i++){
sum += A.get(i);
if(A.get(i) == 0){
if((rightIndex - leftIndex) < 1 ){
leftIndex = i;
rightIndex = i;
}
}
if(sum == 0){
if((rightIndex - leftIndex) < (i+1) ){
leftIndex = 0;
rightIndex = i;
}
}
if(map.containsKey(sum)){
if((rightIndex - leftIndex) < (i-map.get(sum)-1) ){
leftIndex = map.get(sum)+1;
rightIndex = i;
}
}
else{
map.put(sum,i);
}
}
ArrayList<Integer> r = new ArrayList<>();
if(leftIndex!=-1){
for(int i=leftIndex;i<=rightIndex;i++){
r.add(A.get(i));
}
}
return r;
}
public static void main(String[] args) {
System.out.println(new LargestContZero().lszero(new ArrayList<>(Arrays.asList(1,2,-2,4,-4))));
}
}