Vnikku
BAN USERstatic int findLength(String s) {
int start = 0;
int end = 0;
int maxLength = 0;
// create a window with only one zero
while (end < s.length() && s.charAt(end) == '1')
end++;
end++;
// now shift window such that there can only be one zero
while (end < s.length()) {
// move end till second zero
while (end < s.length() && s.charAt(end) == '1')
end++;
// update maxLength with window length if window length is greater than maxLength
if (maxLength < end-start)
maxLength = end-start;
// now shift the whole window such that previous zero is out and the second zero is in
while (start < end && s.charAt(start) == '1')
start++;
start++;
end++;
}
return maxLength;
}
static int findLength(String s) {
int start = 0;
int end = 0;
int maxLength = 0;
// create a window with only one zero
while (end < s.length() && s.charAt(end) == '1')
end++;
end++;
// now shift window such that there can only be one zero
while (end < s.length()) {
// move end till second zero
while (end < s.length() && s.charAt(end) == '1')
end++;
// update maxLength with window length if window length is greater than maxLength
if (maxLength < end-start)
maxLength = end-start;
// now shift the whole window such that previous zero is out and the second zero is in
while (start < end && s.charAt(start) == '1')
start++;
start++;
end++;
}
return maxLength;
}
I think the following code should work
public static void alternate(int[] a) {
int p = 1;
int n = 1;
boolean findPositive = false;
if (a[0] < 0) {
findPositive = true;
}
int t;
for (int i = 1; i < a.length && p < a.length && n < a.length; i++) {
if (findPositive) {
while (p < a.length && a[p] < 0) {
p++;
}
t = p++;
} else {
while (n < a.length && a[n] >= 0) {
n++;
}
t = n++;
}
if (t<a.length) {
swap(a, t, i);
findPositive = !findPositive;
}
}
}
@Jim: for {-1 -4 2 3 4 5 6 7 -1} input, this is returning {-1 2 -4 3 -1 5 6 7 4 } which is correct. Can you please point out the mistakes that you see.
- Vnikku August 29, 2014