AlgoMaster Logo

Max Consecutive Ones

Last Updated: March 31, 2026

easy

Understanding the Problem

We have an array that only contains 0's and 1's, and we need to find the longest streak of consecutive 1's. Think of it like counting the longest winning streak in a series of games where 1 means a win and 0 means a loss.

The key observation is simple: as we scan through the array, we maintain a running count of consecutive 1's. Every time we hit a 0, the streak breaks and we reset the count. At each step, we keep track of the maximum streak we've seen so far. That's really all there is to it. The challenge isn't finding a clever algorithm, it's implementing the straightforward one cleanly without off-by-one errors.

Key Constraints:

  • 1 <= nums.length <= 10^5 → With n up to 100,000, we need O(n) or O(n log n). An O(n^2) approach (checking every subarray) would be 10 billion operations, which is too slow.
  • nums[i] is either 0 or 1 → This is a binary array. We don't need to worry about negative numbers, large values, or any other edge cases related to element values. The only two states are "part of a streak" or "streak breaker."

Approach 1: Brute Force (Check All Subarrays)

Intuition

The most straightforward approach: for every position in the array, check how long the streak of consecutive 1's starting at that position is. Then take the maximum across all starting positions.

This is what you'd do if you were scanning through the array by hand and being extra careful. Pick a starting index, count how many 1's follow in a row, write that down, move to the next starting index, and repeat.

Algorithm

  1. Initialize maxCount = 0 to track the best streak found.
  2. For each index i from 0 to n - 1:
    • If nums[i] is 1, start counting consecutive 1's from index i.
    • Use an inner loop starting at i, incrementing a counter while elements are 1.
    • Update maxCount with the streak length if it's larger.
  3. Return maxCount.

Example Walkthrough

1Initialize: maxCount=0, start scanning from i=0
0
1
i
1
1
2
0
3
1
4
1
5
1
1/6

Code

This brute force recounts the same 1's from every starting position in a streak. What if we just kept a running count that grows with each 1 and resets at each 0?

Approach 2: Single Pass (Running Counter)

Intuition

Here's the key insight: we don't need to restart counting from each position. We can just walk through the array once, keeping a running counter. When we see a 1, we increment the counter. When we see a 0, the streak is broken, so we reset the counter to 0. At every step, we check if the current streak is the longest we've seen.

Algorithm

  1. Initialize maxCount = 0 and count = 0.
  2. Iterate through each element in nums.
  3. If the element is 1, increment count.
  4. If the element is 0, reset count to 0.
  5. After each element, update maxCount = max(maxCount, count).
  6. Return maxCount.

Example Walkthrough

1Initialize: count=0, maxCount=0, i=0
0
1
i
1
1
2
0
3
1
4
1
5
1
1/6

Code