Consecutive ones with a twist in JavaScript

JavascriptWeb DevelopmentFront End Technology

Problem

We are required to write a JavaScript function that takes in a binary array (an array that consists of only 0 and 1), arr, as the only argument. Our function should find the maximum number of consecutive 1s in this array if we can flip at most one 0.

For example, if the input to the function is −

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

Then the output should be −

const output = 4;

Output Explanation

If we flip the 0 at index 1 in the array, we will get 4 consecutive 1s.

Example

The code for this will be −

 Live Demo

const arr = [1, 0, 1, 1, 0];
const findMaximumOne = (nums = []) => {
   let count = 0;
   let first = -1;
   let i =0, j = 0;
   let res = -Infinity;
   while(j < nums.length){
      if(nums[j] === 1){
         res = Math.max(res, j-i+1);
      }else{
         count++;
         if(count==2){
            i = first + 1;
            count--;
         };
         first = j;
      };
      j++;
   };
   return res;
};
console.log(findMaximumOne(arr));

Output

And the output in the console will be −

4
raja
Published on 04-Mar-2021 10:26:26
Advertisements