Finding maximum number of consecutive 1's in a binary array in JavaScript


We are required to write a JavaScript function that takes in a binary array (an array that consists of 0 or 1 only) as the only argument.

The function should find the length of that consecutive subarray of the array that consists of only 1 and return it.

For example −

If the input array is −

const arr = [1, 0, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 0, 1];

Then the output should be −

const output = 4;

We will use the sliding window algorithm to capture the largest window (largest in size) that consists of only 1.

Example

The code for this will be −

 Live Demo

const arr = [1, 0, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 0, 1];
const findMaxConsecutiveOnes = (arr = []) => {
   let left = 0;
   let right = 0;
   let max = 0;
   while (right < arr.length) {
      if (arr[right] === 0) {
         if (right - left > max) {
            max = right - left
         };
         right++;
         left = right;
      } else {
         right++
      };
   };
   return right - left > max ? right - left : max;
}
console.log(findMaxConsecutiveOnes(arr));

Output

And the output in the console will be −

4

Updated on: 26-Feb-2021

246 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements