How do I find a maximum number of consecutive non-zero values in the array?

Hi @javagar ,

Looks like your JavaScript solution doesn’t work ! :wink:

With your function :

console.log(maximumConsecutiveNonZero([0, 0, 1, 0])); // -> 1

(which should be 2)

It’s because you need to remember if you already found a zero before “closing” the previous sequence of zeros.

This is a more conventional solution in Java which can handle all the edges cases :

int maximumConsecutiveNonZero(int[] array) {
  if (array.length == 0) return 0;
  
  boolean alreadyFoundZero = false;

  int maxZeroCount = 0;
  int zeroCount = 1;

  for (int i = 0; i < array.length; i++) {
    // We found a zero
    if (array[i] == 0) {
      if (alreadyFoundZero) { // We are counting a sequence
        zeroCount++;
      } else { // It's the beginning of a sequence
        alreadyFoundZero = true;
        zeroCount = 1;
      }
    } else if (alreadyFoundZero) { // It's not a zero and we were counting a sequence
      // Update the maximum
      if (zeroCount > maxZeroCount) {
        maxZeroCount = zeroCount;
      }
      
      // Stop the sequence
      alreadyFoundZero = false;
    }
  }
  
  // Check if the last element is a zero, if so return the number of zeros
  int lastElement = array[array.length - 1];

  return (lastElement == 0) ? zeroCount : maxZeroCount;
}

And the tests :

final int[] values = {};                 // -> 0
final int[] values = {0};                // -> 1
final int[] values = {0, 0, 0};          // -> 3
final int[] values = {1};                // -> 0
final int[] values = {1, 1, 1};          // -> 0
final int[] values = {0, 1, 1};          // -> 1
final int[] values = {1, 1, 0};          // -> 1
final int[] values = {1, 1, 0, 1, 1, 1}; // -> 1
final int[] values = {1, 1, 1, 0, 1, 1}; // -> 1