Answers for "find consecutives"

0

find consecutives

var findMaxConsecutiveOnes = function (arr, number) {
   //check for boundries
   if(!number || !arr.length) return;

  // maximum number of consectuives
  let max = 0;

  // count homy many consecutives before it ends (why it's 1 ? because a lonely number is still counted)
  let counter = 1;

  // you can ignore the next 2 variable if you want to use for loop instead of while
  let length = arr.length;
  let i = 1; // counting from index 1 because we are checking against index-1
  while (i < length) {

    if (arr[i] == arr[i - 1]) {

      // boom, we have a consecutive, count it now
      counter++;
    } else {

      // rest to 1
      counter = 1;
    }

    // always update the max variable to the new max value
    max = Math.max(counter, max);

    //for the sake of iteration
    i++;
  }
  return max== number;
};
console.log(findMaxConsecutiveOnes([5, 5, 5, 1, 1, 1, 1, 1]));
Posted by: Guest on May-06-2021

Browse Popular Code Answers by Language