888216. Max consecutive one

Easy

Max Consecutive One

Slug: max-consecutive-one

Difficulty: Easy

Id: 888216

Topic Tags: Arrays

Company Tags: None

Summary

Given an array of binary digits (0s and 1s), find the maximum number of consecutive ones in the array.

Detailed Explanation

To solve this problem, we can iterate through the array and keep track of the maximum length of consecutive ones encountered so far. We start by initializing a variable maxConsecutiveOnes to 0, which will store the maximum length of consecutive ones found.

Here's the step-by-step breakdown:

  1. Initialize maxConsecutiveOnes to 0.
  2. Iterate through the array from left to right.
  3. For each element, check if it is a 1. If it is:
    • Reset the count of consecutive ones to 1 (since we just found one).
    • Update maxConsecutiveOnes if the current count is greater than the previous maximum.
  4. Continue iterating until the end of the array.

Time complexity: O(n), where n is the length of the input array, since we only need to make a single pass through the array.

Space complexity: O(1), since we only use a constant amount of space to store the maxConsecutiveOnes variable.

Optimized Solutions

Java

View on GeeksforGeeks
public int maxConsecutiveOnes(int[] arr) {
    int maxConsecutiveOnes = 0;
    int currentCount = 0;

    for (int i : arr) {
        if (i == 1) {
            currentCount++;
            maxConsecutiveOnes = Math.max(maxConsecutiveOnes, currentCount);
        } else {
            currentCount = 0;
        }
    }

    return maxConsecutiveOnes;
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.