Maximum Consecutive Ones

Given a binary array containing only 0s and 1s, return the length of the longest run of consecutive 1s.

EasyOptionalSliding Window
Solve This Problem

Video Solution

Video coming soon

We're producing a video walkthrough — check back soon.

Problem Overview

Given a binary array containing only 0s and 1s, return the length of the longest run of consecutive 1s.

Why solve this?

The gentlest possible taste of a sliding window: a window that only ever grows or resets, never shrinks from the middle. It's the natural stepping stone before this course's real fixed- and variable-size window problems.

Pattern Recognition

Whenever a problem asks for the longest or shortest contiguous run satisfying a simple condition, track a running window length that resets the instant the condition breaks.

Prerequisites

  • No prior lessons required.

Hints

  1. You don't need to track window start/end indices — just a running count.
  2. Every time you see a 1, extend the current run; every time you see a 0, the run resets to zero.
  3. Keep a separate variable for the best run seen so far, updated after every step.

Approach

Scan the array while keeping two counters: the current run length and the best run seen so far. Seeing a 1 extends the current run by one; seeing a 0 resets the current run to zero. After every step, update the best-so-far if the current run is longer. One pass, constant extra space.

Code

Solution.java
class Solution {
    public int findMaxConsecutiveOnes(int[] nums) {
        int best = 0, current = 0;
        for (int num : nums) {
            current = (num == 1) ? current + 1 : 0;
            best = Math.max(best, current);
        }
        return best;
    }
}
Time: O(n)Space: O(1)

Related Problems

Back to Arrays