Coding problem · Easy · Basics

Longest Run of Ones

Easy Algorithms & data structures

nums contains only 0s and 1s. Return the length of the longest run of consecutive 1s.

Example 1

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

Example 2

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

Hints

Hint 1

Count the current run; reset it to 0 when you see a 0.

Hint 2

Track the best run seen so far.

Write and run your solution

Loading the editor… (JavaScript is required to run code in your browser.)

Solution and explanation

Show the solution

Time O(n) · Space O(1)

One pass with two counters: current grows on 1 and resets on 0, best keeps the maximum.

Reference solution

function maxConsecutiveOnes(nums) {
  let best = 0, current = 0;
  for (const n of nums) {
    current = n === 1 ? current + 1 : 0;
    best = Math.max(best, current);
  }
  return best;
}

Was this page helpful?