380/670

380. Max Consecutive Ones

Easy

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

A streak is a run of consecutive positions that all hold 1; a single 0 anywhere ends it. If the array contains no 1 at all, the answer is 0.

Example 1 — runs of consecutive 1sTwo runs of 1s, lengths 2 and 3, separated by a 0. The answer is the longer run: 3.
110111run of 2run of 3the 0 breaks the streaklongest run = 3

Example 1:

Input: nums = [1, 1, 0, 1, 1, 1]

Output: 3

Explanation: There are two runs of 1s: one of length 2 at the start and one of length 3 at the end. The longest is 3.

Example 2:

Input: nums = [1, 0, 1, 1, 0, 1]

Output: 2

Explanation: The runs of 1s have lengths 1, 2, and 1. The longest is 2.

Constraints:

  • 1 ≤ nums.length ≤ 10⁵
  • nums[i] is 0 or 1

Hints:

You never need to look at an element twice. As you scan left to right, what one number describes the situation at position i?

Keep a running counter of the current streak: +1 on every 1, reset to 0 on every 0. The answer is the largest value the counter ever reaches — take the max on every step so the final streak isn't missed.

▶ Run checks these sample cases. Submit also runs hidden edge cases.

Input: nums = [1, 1, 0, 1, 1, 1]

Expected output: 3