Find the maximum number of consecutive 1s in a binary array.
Problem Statement
Given a binary array, find the maximum number of consecutive 1s in the array.
Examples
Input: arr = [1, 1, 0, 1, 1, 1]
Output: 3
Explanation: The longest sequence is 3.
Constraints
Standard constraints
Complexity
Time Complexity: O(N)
Space Complexity: O(1)
Hints
š” Hint 1:
Track the running streak of consecutive ones with a counter variable.
š” Hint 2:
Whenever you see a 1, increment the streak and update maxCount = Math.max(maxCount, streak).
š” Hint 3:
Whenever you see a 0, reset the streak counter back to 0.
Editorial & Approach
Problem Overview & Intuition
Iterate through the binary array while maintaining a counter for the current consecutive sequence of ones. Update the maximum streak whenever a 1 is seen, and reset the streak counter whenever a 0 appears.
Step-by-Step Approach
- Initialize
maxCount = 0andcurrentCount = 0. - Iterate through each number in
arr. - If
num === 1, incrementcurrentCount++and updatemaxCount = Math.max(maxCount, currentCount). - If
num === 0, resetcurrentCount = 0. - Return
maxCount.
Optimal Implementation (JavaScript)
function findMaxConsecutiveOnes(arr) {
let maxCount = 0, currentCount = 0;
for (let num of arr) {
if (num === 1) {
currentCount++;
if (currentCount > maxCount) maxCount = currentCount;
} else {
currentCount = 0;
}
}
return maxCount;
}
Complexity Analysis
Time Complexity
O(N) ā single linear pass through the array.
Space Complexity
O(1) ā only two scalar counters.
Edge Cases & Corner Traps Handled
- Array of all zeroes: returns 0.
- Array of all ones: returns array length.
- Alternating ones and zeroes [1, 0, 1, 0]: returns 1.