Skip to content

Commit 38a97ae

Browse files
committed
replace one 0 to get longest ones
1 parent a3d34fc commit 38a97ae

File tree

1 file changed

+41
-2
lines changed

1 file changed

+41
-2
lines changed

src/Array/ReplaceZeroOneToFindLongest1.java

Lines changed: 41 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,12 +5,51 @@
55
*/
66
public class ReplaceZeroOneToFindLongest1 {
77
public static void main(String[] strings) {
8-
int[] array = new int[]{1, 0, 1, 1, 0, 1, 0, 1, 1, 1, 0, 1};
8+
/*
9+
int[] array = new int[]{1, 0, 1, 1, 0,1, 0, 1, 1, 1, 0, 0};
10+
*/
11+
int[] array = new int[]{1, 1, 1, 1, 0,1, 1, 1, 1, 1, 1, 1};
912

10-
int start, rep, length;
13+
int index = -1;
14+
int maxlen = 0;
15+
16+
int prevp = -1;
17+
Integer prevprev0 = null;
1118

1219
for (int x = 0; x < array.length; x++) {
20+
if (array[x] == 0) {
21+
if (prevp == -1) {
22+
prevp = x;
23+
index = x;
24+
}else{
25+
if(prevprev0 == null){
26+
//only one zero found till now
27+
if(x > maxlen){
28+
index = prevp;
29+
maxlen = x;
30+
}
31+
}else if(x-prevprev0-1 > maxlen){
32+
//prev prev 0 excluded
33+
index = prevp;
34+
maxlen = x-prevprev0-1;
35+
}
36+
prevprev0 = prevp;
37+
prevp = x;
38+
}
39+
40+
}
41+
}
1342

43+
//check if last is 1
44+
if(array[array.length-1] == 1 && prevprev0 != null){
45+
if((array.length-1)-prevprev0 > maxlen){
46+
index = prevp;
47+
}
48+
}
49+
if(prevprev0 == null && prevp == -1){
50+
System.out.print(-1);
51+
}else{
52+
System.out.println(index);
1453
}
1554

1655
}

0 commit comments

Comments
 (0)