Algorithm

Max Consecutive Ones

Arrays & Strings Pattern

Max Consecutive Ones

Given a binary array nums, return the maximum number of consecutive 1s in the array.

CONSTRAINTS
  • 1 <= nums.length <= 10⁵
  • nums[i] is either 0 or 1
EXAMPLE 1
Input: nums = [1,1,0,1,1,1]
Output: 3
Two runs exist: length 2 and length 3. The 0 between them breaks the streak — runs cannot jump over it.
EXAMPLE 2
Input: nums = [1,0,1,1,0,1]
Output: 2
Runs are 1, 2, and 1 long. The longest is 2.
EXAMPLE 3
Input: nums = [0,0,0]
Output: 0
No 1s at all, so no run ever starts. The answer is 0, not -1 or an error.
EXAMPLE 4
Input: nums = [1,1,1,1]
Output: 4
No walls anywhere — the single run spans the whole array.
Does 'consecutive' mean strictly adjacent — a run broken by a single 0 doesn't count as one run?
Correct. A run is an unbroken block of 1s. Even one 0 ends it; counting resumes from zero afterward.
Can I rely on the array containing only 0s and 1s?
Yes, that is guaranteed. No other values will appear.
Should I return the run's length or its position?
Just the length of the longest run. If the array is all 1s, that is simply the array's length; if all 0s, it is 0.

Finding the longest streak of 1s is about keeping a simple counter and resetting it the moment you hit a 0. A 0 acts as a wall that kills the current streak.

The Single Pass (O(N))

We walk through the array once with a current counter.
- On every 1: Increment the counter and update our global max.
- On every 0: Reset the counter to zero.

python
max_ones = current = 0
for x in nums:
    if x == 1:
        current += 1
        max_ones = max(max_ones, current)
    else:
        current = 0
return max_ones
Worked Example:[1, 1, 0, 1, 1, 1]
0
1
x
1
1
2
0
3
1
4
1
5
1
We find a 1, which increases our consecutive streak to 1 and updates our maximum streak to 1.
0
1
1
1
x
2
0
3
1
4
1
5
1
We find another 1, bringing our running consecutive streak to 2. Our maximum streak is updated to 2.
0
1
1
1
2
0
x
3
1
4
1
5
1
We hit a 0, which breaks our streak. We reset our running counter to 0, but preserve our maximum streak of 2.
0
1
1
1
2
0
3
1
x
4
1
5
1
We encounter a 1, starting a new consecutive streak. Our running counter becomes 1, and our maximum streak remains 2.
0
1
1
1
2
0
3
1
4
1
x
5
1
We encounter another 1, incrementing our running consecutive streak to 2. Our maximum streak remains 2.
0
1
1
1
2
0
3
1
4
1
5
1
x
We find a third consecutive 1, raising our running streak to 3. This sets a new maximum streak of 3, which is our final result.
Interactive Strategy Visualization

The Streak Tracker

Strategy: Scan & Remember
1
1
0
1
1
1
0
1
Current Streak
1
Global Record
1
Found a 1! Streak starts at 1. 🔥
ONE-PASS SCAN

We only need to look at each number once. If it's a 1, we add to our streak. If it's a 0, we start over.

REPLACEMENT

Whenever our current streak grows larger than our record, we update the record.

O(N) Single Scan — Optimal