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.
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: 3Example 2
Input: nums = [1,0,1,1,0,1]
Output: 2Constraints
1 <= nums.length <= 100,000—nums[i]is either0or1.
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;
}