Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
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 −
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
Advertisements