Max Consecutive Ones

Easy· single pass

Problem

Given a binary array, find the length of the longest run of consecutive 1s. A single pass should be enough.

Examples

Input: nums = [1,1,0,1,1,1,0,1]
Output: 3
The run in the middle (indices 3 to 5) has three 1s in a row.
Input: nums = [0,0]
Output: 0

Constraints

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

Hints & approach

Hint 1

You only need to know the length of the run you are currently in.

Hint 2

Reset the running length whenever you see a 0, and record the best seen so far.

Approachtry the hints first

Walk the array with a running counter. On a 1, increment the counter and update the best answer; on a 0, reset the counter to zero. The best value seen during the scan is the answer. No extra storage is needed beyond two integers.

Time O(n) · Space O(1)

Output
Call your solution with a test case and Run. For the full judge, submit on LeetCode.