- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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;

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

The code for this will be −

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));

And the output in the console will be −

6

- Related Questions & Answers
- Maximum sum of n consecutive elements of array in JavaScript
- 1 to n bit numbers with no consecutive 1s in binary representation?
- N consecutive odd numbers JavaScript
- Count number of 1s in the array after N moves in C
- Counting the number of 1s upto n in JavaScript
- Find consecutive 1s of length >= n in binary representation of a number in C++
- Program to find longest consecutive run of 1s in binary form of n in Python
- Program to find remainder after dividing n number of 1s by m in Python
- Largest permutation after at most k swaps in C++
- Longest string consisting of n consecutive strings in JavaScript
- Find the number of binary strings of length N with at least 3 consecutive 1s in C++
- Program to find minimum swaps needed to group all 1s together in Python
- Maximum sum after repeatedly dividing N by a divisor in C++
- Smallest number after removing n digits in JavaScript
- Program to find number of sequences after adjacent k swaps and at most k swaps in Python

Advertisements