Programming problem: Max Consecutive Ones

Track the current streak of 1s and reset on 0. A single pass through the array in O(n) time and O(1) space gives you the maximum consecutive count — no extra data structures needed.

Programming problem: Max Consecutive Ones

Question

You are given a binary array nums, return the maximum number of consecutive 1's in the array.

Example 1

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

Example 2

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

Constraints

  • 1 <= nums.length <= 100,000nums[i] is either 0 or 1.

Solution

function findMaxConsecutiveOnes(nums: number[]): number {
  let max: number = 0;
  let current: number = 0;

  for (const num of nums) {
    current = num === 1 ? current + 1 : 0;
    max = Math.max(current, max);
  }

  return max;
}