Explorer
Data Structures & Algorithms

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

  1. Initialize maxCount = 0 and currentCount = 0.
  2. Iterate through each number in arr.
  3. If num === 1, increment currentCount++ and update maxCount = Math.max(maxCount, currentCount).
  4. If num === 0, reset currentCount = 0.
  5. 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.

Maximum Consecutive Ones

Easy
Given a binary array, find the maximum number of consecutive 1s in the array.
Example Scenarios
1Example 1
Input: arr = [1, 1, 0, 1, 1, 1]
Output: 3
Explanation:

The longest sequence is 3.

Constraints
•Standard constraints
Editor
Loading Editor...
arr =
[1, 1, 0, 1, 1, 1]
Output:Click "Run" above to execute and verify your code here.
3