Max Consecutive Ones
Given a binary array nums, return the maximum number of consecutive 1s.
Intuition
Walk the array counting the current streak of 1s. A 0 breaks the streak, so reset the counter. Remember the longest streak seen.
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.
Approach
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.
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.
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.
Solution & live demo
Common pitfalls
Updating the best only at the end
for n in nums:
if n == 1: streak += 1
else: streak = 0
return streak 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
if n == 1: streak += 1
if n == 1:
streak += 1
best = max(best, streak)
else:
streak = 0Without the reset the counter simply totals all ones in the array, ignoring whether they were consecutive at all.
Seeding best at 1
best = 1
best = streak = 0
An array of all zeros has a longest run of 0. Starting at 1 claims a run that never existed.
Edge cases
streak never resets, so best equals the array length.
streak stays 0 throughout; best returns 0.
best is updated on every 1, so a streak that ends only at the array's end is still captured.