AlgoMaster Logo

Max Consecutive Ones

easyFrequency5 min readUpdated June 23, 2026

Understanding the Problem

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

As we scan through the array, we maintain a running count of consecutive 1's. Every time we reach a 0, the streak breaks and the count resets. At each step, we record the largest count seen so far. The difficulty here is not the algorithm but implementing the scan 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

For every position in the array, count how long the run of consecutive 1's starting at that position is. The answer is the maximum of those counts across all starting positions. Pick a starting index, count how many 1's follow in a row, record that length, 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

The brute force recounts the same 1's from every starting position inside a run. A single pass that keeps a running count, growing it on each 1 and resetting it on each 0, avoids that repeated work.

Approach 2: Single Pass (Running Counter)

Intuition

There is no need to restart counting from each position. Walk through the array once, keeping a running counter. On a 1, increment the counter. On a 0, the streak is broken, so reset the counter to 0. After each element, compare the current streak against the longest seen so far.

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