LeetCode #485 Easy

Max Consecutive Ones

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

array
Open on LeetCode ↗
02

Intuition

Walk the array counting the current streak of 1s. A 0 breaks the streak, so reset the counter. Remember the longest streak seen.

How to spot this pattern

A running-streak counter — the simplest possible sliding window, where a zero resets the window to nothing. Worth recognising as the base case of the harder variants: max-consecutive-ones III allows flipping k zeros, at which point the reset becomes a shrink and you need a real two-pointer window.

03

Approach

1

Why re-counting from each index is wasteful

A first instinct is: for every position, count how long the run of 1s starting there is, and keep the longest — O(n²). But notice the runs overlap heavily; once you've measured a run, restarting the count one position later re-walks almost the same cells. We can measure every run in a single forward sweep instead.

2

Maintain the current streak as you walk

Keep one counter, streak, for the length of the run of 1s ending at the current position. A 1 extends the run (streak += 1); a 0 breaks it, so the run ends and we reset (streak = 0). That single number captures everything we need to know about the immediate past.

3

Record the best at every 1

Each time streak grows, compare it to best. Updating best on every 1 — not just at zeros or at the end — is what makes a run that reaches the very end of the array still count. Return best. O(n) time, O(1) space, one pass.

04

Solution & live demo

1class Solution:
2 def findMaxConsecutiveOnes(self, nums):
3 best = streak = 0
4 for n in nums:
5 if n == 1:
6 streak += 1
7 best = max(best, streak)
8 else:
9 streak = 0
10 return best
05

Common pitfalls

Updating the best only at the end

✗ Wrong
for n in nums:
    if n == 1: streak += 1
    else: streak = 0
return streak
✓ Right
    if n == 1:
        streak += 1
        best = max(best, streak)

streak is reset by any later zero, so returning it reports the trailing run rather than the longest. The maximum has to be captured while the streak is still alive.

Forgetting to reset on a zero

✗ Wrong
if n == 1: streak += 1
✓ Right
if n == 1:
    streak += 1
    best = max(best, streak)
else:
    streak = 0

Without the reset the counter simply totals all ones in the array, ignoring whether they were consecutive at all.

Seeding best at 1

✗ Wrong
best = 1
✓ Right
best = streak = 0

An array of all zeros has a longest run of 0. Starting at 1 claims a run that never existed.

06

Edge cases

All ones, e.g. [1,1,1]

streak never resets, so best equals the array length.

All zeros

streak stays 0 throughout; best returns 0.

Trailing run of ones

best is updated on every 1, so a streak that ends only at the array's end is still captured.

07

Complexity

Time
O(n)
Space
O(1)
One pass; two counters.