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.

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

python
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

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.

06

Complexity

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