Why count every time all zero? Just look if this index is the first zero, then check if index + max_zero_strike + 1 == 0
. If true, check the value before and after. That way you may be a bit more efficient.
big edit: trying to make the code work, i've found out this solution, that drift a lot form original code, but not so much from original concept, and also it is a lot clearer.
new (working) code:
private static int getMax(int[] values) {
int maxLength = 0;
for (int i = 0; i < values.length; i+=1+maxLength) { // here we are looking for the first zero. if lenght remaining is lesser than actual max zero-strike, no way we caund found a better.
if (values[i] == 0) { // is zero
//find leftmost zero
int tmpLeft = 0;
while(tmpLeft < i && values[i-tmpLeft-1] == 0){
tmpLeft++;
}
//find righmost zero
int tmpRight = 0;
while(tmpRight+i < values.length && values[i+tmpRight] == 0){
tmpRight++;
}
maxLength = Math.max(maxLength, tmpLeft+tmpRight);
}
}
return maxLength;
}
Also runned some benchmark versus OP code (random sample of value generated with values[a] = r.nextInt(3); ). (banchamrk full code: https://gist.github.com/MauroMombelli/b68641a785f3e93fd410)
for array of size == 10, op code is 2 time faster on this pc (1000 nanosec vs 2000 nanosec)
for array of size == 100 code execution are similar
for array == 1000 my code is faster, op code take fixed 5700 nanosec, my code from 3000 to 3500
for array == 1000, but value from 0 to 9, op code take fixed 3079nanosec, my code from 2200 to 2600
for array == 1000 (0-9) op code take 30.000-47.000 mine 10.000-13.000
old (not working) code:
public class ZeroSeriesLength {
public static void main(String[] args) {
int[] values = {1, 2, 0, 0, 2, 4, 0, 2, 0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 7, 0};
int maxLength = 0;
for (int i = 0; i < values.length-maxLength ; i++) { //here we are looking for the first zero. if lenght remaining is lesser than actual max zero-strike, no way we caund found a better.
if (values[i] == 0) { //first zero
int tmpCheck = i+maxLength+1;//shot for a streak with at least one more zero
while (tmpCheck > i && values[tmpCheck] == 0){
tmpCheck--;
}
if (tmpCheck == i){ //true if those between i and i+maxLength+1 was all zero!
//we have a strike bigger than actual by at least 1!
maxLength++;
//now check for additional zero on the right, but please don't overflow
while(i + maxLength + 1 < values.length && values[i+maxLength+1] == 0){
maxLength++;
}
}
i+=maxLength+1; //no need to check again all that zero and last not-zero!
}
}
System.out.println("Maximum number of consecutive zeros : " + maxLength);
}
}
if (tempLength > maxLength) { maxLength = tempLength; }
in the else statement. \$\endgroup\$