← All Lessons Lesson 50 / 68
Lesson 50

Finding the Longest Run of 1's in a Binary Array

Counting Consecutive 1's

A binary array is just a list of numbers where every value is either 0 or 1. Nothing else is allowed. Think of it like a row of light switches, where 1 means "on" and 0 means "off".

Our task is simple to say: look through the array and find the longest unbroken streak of 1's. By "unbroken" we mean the 1's sit right next to each other, with no 0 between them. We then return how long that longest streak is.

Understanding with examples

Take this array:

arr = [1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0]

Let's walk along it and notice the groups of 1's:

  • At the start: 1, 1, 1 → a streak of 3.
  • Then some 0s break the chain.
  • Later: 1, 1, 1, 1 → a streak of 4.

The biggest streak we saw is 4, so the answer is 4.

Now the second example:

arr = [1, 1, 0, 0, 0, 1, 1, 0, 1, 0]

  • First group: 1, 1 → streak of 2.
  • Next group: 1, 1 → streak of 2.
  • Last single 1 → streak of 1.

The longest is 2, so the answer is 2.

The idea behind the solution

You do not need to remember the whole array or do anything fancy. You only need to walk through it once, keeping track of two simple things:

  1. count — how long the current streak of 1's is *right now*.
  2. maxCount — the longest streak you have seen *so far*.

Here is the plain rule for each number as you pass over it:

  • If the current number is 1, the streak continues, so add one to count. Then check: if count is now bigger than maxCount, update maxCount to match it.
  • If the current number is 0, the streak is broken. Reset count back to 0 and keep moving.

When you reach the end of the array, maxCount holds the answer.

This works because count always tells you the length of the streak you are currently inside, and maxCount quietly remembers the best one you ever entered. A single pass is enough, which makes this both easy to write and fast to run.

Filling in the function

The problem gives you a function shell to complete:

class Solution {
public:
    int consecutiveOnes(vector<int> &arr) {

    }
};

Inside consecutiveOnes, you would create your count and maxCount variables (both starting at 0), loop through every element of arr applying the rule above, and finally return maxCount.

Finding the Longest Run of 1's in a Binary Array
Diagram — click to zoom (scroll / drag to pan)