Max Consecutive Ones

easy

You're given a binary array nums — every element is either 0 or 1. Return the length of the longest unbroken run of 1s in the array.

A run breaks the moment you hit a 0. So you're looking for the widest stretch of consecutive 1s, counting nothing but 1s inside it.

Hints

You don't need to remember where a run started — only how long the current one is.
What should happen to your running count the moment you see a 0?
Sweep once: add 1 to a counter on every 1, reset it to 0 on every 0, and keep the largest counter value you ever saw.

Common doubts

No. Two integers — current and best — are enough. Space is O(1).
There are no 1s at all, so the longest run has length 0. The counter never leaves 0.
The counter climbs to nums.length and best ends up equal to it — the run is the entire array.

Interview follow-ups

That becomes the "longest ones with at most k flips" variant — slide a window that may contain up to k zeros, growing the right edge and shrinking the left whenever the zero-budget is exceeded.
The O(1)-space single pass already handles a stream perfectly — you never need to hold the whole array in memory.

Fun facts

  • The reset-on-boundary trick is the same skeleton as Kadane's algorithm for maximum subarray sum — swap 'reset on 0' for 'reset when the running sum goes negative.'
  • Counting the longest streak is exactly how habit-tracker and gaming 'win streak' features work under the hood.

Asked at

AmazonGoogleMicrosoftAdobe
Frequently Sometimes Occasionally
Example 1
Input: nums = [1,1,0,1,1,1]
Output: 3
The first two `1`s form a run of length 2; the last three form a run of length 3. The longest is 3.
Example 2
Input: nums = [1,0,1,1,0,1]
Output: 2
The best run is the middle `1,1`, of length 2.
Constraints

- 1 <= nums.length <= 10^5 - nums[i] is either 0 or 1.

Solve this problem →