Learn how to find the maximum consecutive one’s or zero’s in a binary array.
Input: [1, 0, 0, 0, 1, 0, 1, 0, 1, 1, 1, 1] Output: 4
Maximum consecutive one’s in a binary array
Conceptually this is how the solution works.
- We use two different trackers, one to track the current count and one to store the max count.
- Iterate the array and keep increasing the current count if it is one. Once there is different element update the max count and reset the current count.
const getMaxLength = (arr, n = arr.length) => { let current = 0; let max = 0; for(let i = 0; i < n; i++){ if(!arr[i]){ current = 0; }else{ current++; max = Math.max(max, current); } } return max; }
Input: const arr = [1, 0, 0, 0, 1, 0, 1, 0, 1, 1, 1, 1]; console.log(getMaxLength(arr)); Output: 4
Time complexity: O(n).
Space complexity: O(1).