Maximum consecutive 1s after n swaps in JavaScript

JavascriptWeb DevelopmentFront End Technology

Problem

We are required to write a JavaScript function that takes in a binary arr (array that contains only 0 or 1), arr, as the first argument, and a number, num, as the second argument.

We can change at most num 0s present in the array to 1s, and our function should return the length of the longest (contiguous) subarray that contains only 1s after making these changes.

For example, if the input to the function is −

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

Then the output should be −

const output = 6;

Output Explanation

Because after changing two zeros to 1, the last 6 elements of the array will be 1.

Example

The code for this will be −

 Live Demo

const arr = [1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0];
const num = 2;
const longestOnes = (arr = [], num = 1) => {
   let max = 0;
   let left = 0;
   let curr = num;
   for(let right = 0; right < arr.length; right++){
      if(arr[right] === 0){
         curr -= 1;
      };
      while(curr < 0){
         if(arr[left] === 0){
            curr += 1;
         };
         left += 1;
      };
      max = Math.max(max, right - left + 1);
   };
   return max;
};
console.log(longestOnes(arr, num));

Output

And the output in the console will be −

6
raja
Published on 09-Apr-2021 08:23:22
Advertisements