Find Maximum Consecutive Ones in Array using Loop - Optimal Algorithm

Visualization Player

Problem Statement

You are given a binary array that consists only of 0s and 1s. Your task is to find the maximum number of consecutive 1s that appear in the array.

In simpler terms, you need to count the longest stretch of 1s that are placed next to each other (without any 0s in between).

If the array is empty, the result should be 0.

Examples

Input Array Max Consecutive 1s Description
[1, 1, 0, 1, 1, 1] 3 The longest sequence of 1s is [1, 1, 1]Visualization
[1, 1, 1, 1] 4 All elements are 1s, so the count is the length of the arrayVisualization
[0, 0, 0] 0 No 1s in the arrayVisualization
[1, 0, 1, 0, 1] 1 All 1s are isolated by 0sVisualization
[0, 1, 1, 0, 1, 1, 1, 0] 3 There are two sequences: [1, 1] and [1, 1, 1]; the longest is length 3Visualization
[1] 1 Single element that is 1Visualization
[0] 0 Single element that is 0Visualization
[] 0 Empty array should return 0Visualization

Solution

Understanding the Problem

We are given a binary array — an array consisting only of 1s and 0s. The goal is to find the length of the longest contiguous sequence of 1s.

That means we want to count how many 1s appear in a row without being interrupted by a 0. As soon as we hit a 0, the streak is broken, and we start counting again.

Step-by-Step Approach (with Example)

Let’s take the example array: [1, 1, 0, 1, 1, 1]

Step 1: Initialize two counters

  • current_count: to keep track of the current streak of 1s.
  • max_count: to remember the highest streak we've seen so far.

Step 2: Loop through the array

  • Start from the first element and go to the end.
  • If the element is 1: increment current_count.
  • If the element is 0: reset current_count to 0.
  • At each step, update max_count to be the maximum of itself and current_count.

Step 3: Final Result

After the loop, max_count will hold the longest stretch of 1s.

Detailed Walkthrough for [1, 1, 0, 1, 1, 1]

  • Start: current_count = 0, max_count = 0
  • Index 0: 1 → current_count = 1, max_count = 1
  • Index 1: 1 → current_count = 2, max_count = 2
  • Index 2: 0 → current_count = 0, max_count = 2
  • Index 3: 1 → current_count = 1, max_count = 2
  • Index 4: 1 → current_count = 2, max_count = 2
  • Index 5: 1 → current_count = 3, max_count = 3

Final answer: 3

Incorporating Edge Cases

1. All 1s: [1, 1, 1, 1]

The entire array is one continuous sequence of 1s → Output: 4

2. All 0s: [0, 0, 0]

No 1s present at all → Output: 0

3. Isolated 1s: [1, 0, 1, 0, 1]

Each 1 is surrounded by 0s → Maximum streak = 1

4. Empty Array: []

No elements means no 1s → Output: 0

Efficiency

This approach uses only one pass through the array (O(n) time complexity) and does not use any extra space. It’s optimal and beginner-friendly.

Algorithm Steps

  1. Given an array arr that contains only 0 and 1.
  2. Initialize two counters: max_count = 0 and current_count = 0.
  3. Iterate through the array:
  4. → If the current element is 1, increment current_count.
  5. → If the current element is 0, reset current_count to 0.
  6. After each step, update max_count if current_count is greater.
  7. After the loop, return max_count.

Code

C
C++
Python
Java
JS
Go
Rust
Kotlin
Swift
TS
#include <stdio.h>

int maxConsecutiveOnes(int arr[], int n) {
    int maxCount = 0, currentCount = 0;
    for (int i = 0; i < n; i++) {
        if (arr[i] == 1) {
            currentCount++;
            if (currentCount > maxCount)
                maxCount = currentCount;
        } else {
            currentCount = 0;
        }
    }
    return maxCount;
}

int main() {
    int arr[] = {1, 1, 0, 1, 1, 1};
    int n = sizeof(arr) / sizeof(arr[0]);
    printf("Max Consecutive Ones: %d\n", maxConsecutiveOnes(arr, n));
    return 0;
}

Time Complexity

CaseTime ComplexityExplanation
Best CaseO(n)Even if the array starts with a long streak of 1s, we still need to check all elements to ensure it's the longest sequence.
Average CaseO(n)The algorithm goes through each element of the array once in a single pass, updating counters as needed.
Worst CaseO(n)In the worst case, such as alternating 1s and 0s, every element must still be processed to determine the maximum streak.

Space Complexity

O(1)

Explanation: The algorithm uses only two variables to keep track of the current and maximum count. No additional space is required.

Problem Statement

You are given a binary array that consists only of 0s and 1s. Your task is to find the maximum number of consecutive 1s that appear in the array.

In simpler terms, you need to count the longest stretch of 1s that are placed next to each other (without any 0s in between).

If the array is empty, the result should be 0.

Examples

Input Array Max Consecutive 1s Description
[1, 1, 0, 1, 1, 1] 3 The longest sequence of 1s is [1, 1, 1]Visualization
[1, 1, 1, 1] 4 All elements are 1s, so the count is the length of the arrayVisualization
[0, 0, 0] 0 No 1s in the arrayVisualization
[1, 0, 1, 0, 1] 1 All 1s are isolated by 0sVisualization
[0, 1, 1, 0, 1, 1, 1, 0] 3 There are two sequences: [1, 1] and [1, 1, 1]; the longest is length 3Visualization
[1] 1 Single element that is 1Visualization
[0] 0 Single element that is 0Visualization
[] 0 Empty array should return 0Visualization

Solution

Understanding the Problem

We are given a binary array — an array consisting only of 1s and 0s. The goal is to find the length of the longest contiguous sequence of 1s.

That means we want to count how many 1s appear in a row without being interrupted by a 0. As soon as we hit a 0, the streak is broken, and we start counting again.

Step-by-Step Approach (with Example)

Let’s take the example array: [1, 1, 0, 1, 1, 1]

Step 1: Initialize two counters

  • current_count: to keep track of the current streak of 1s.
  • max_count: to remember the highest streak we've seen so far.

Step 2: Loop through the array

  • Start from the first element and go to the end.
  • If the element is 1: increment current_count.
  • If the element is 0: reset current_count to 0.
  • At each step, update max_count to be the maximum of itself and current_count.

Step 3: Final Result

After the loop, max_count will hold the longest stretch of 1s.

Detailed Walkthrough for [1, 1, 0, 1, 1, 1]

  • Start: current_count = 0, max_count = 0
  • Index 0: 1 → current_count = 1, max_count = 1
  • Index 1: 1 → current_count = 2, max_count = 2
  • Index 2: 0 → current_count = 0, max_count = 2
  • Index 3: 1 → current_count = 1, max_count = 2
  • Index 4: 1 → current_count = 2, max_count = 2
  • Index 5: 1 → current_count = 3, max_count = 3

Final answer: 3

Incorporating Edge Cases

1. All 1s: [1, 1, 1, 1]

The entire array is one continuous sequence of 1s → Output: 4

2. All 0s: [0, 0, 0]

No 1s present at all → Output: 0

3. Isolated 1s: [1, 0, 1, 0, 1]

Each 1 is surrounded by 0s → Maximum streak = 1

4. Empty Array: []

No elements means no 1s → Output: 0

Efficiency

This approach uses only one pass through the array (O(n) time complexity) and does not use any extra space. It’s optimal and beginner-friendly.

Algorithm Steps

  1. Given an array arr that contains only 0 and 1.
  2. Initialize two counters: max_count = 0 and current_count = 0.
  3. Iterate through the array:
  4. → If the current element is 1, increment current_count.
  5. → If the current element is 0, reset current_count to 0.
  6. After each step, update max_count if current_count is greater.
  7. After the loop, return max_count.

Code

C
C++
Python
Java
JS
Go
Rust
Kotlin
Swift
TS
#include <stdio.h>

int maxConsecutiveOnes(int arr[], int n) {
    int maxCount = 0, currentCount = 0;
    for (int i = 0; i < n; i++) {
        if (arr[i] == 1) {
            currentCount++;
            if (currentCount > maxCount)
                maxCount = currentCount;
        } else {
            currentCount = 0;
        }
    }
    return maxCount;
}

int main() {
    int arr[] = {1, 1, 0, 1, 1, 1};
    int n = sizeof(arr) / sizeof(arr[0]);
    printf("Max Consecutive Ones: %d\n", maxConsecutiveOnes(arr, n));
    return 0;
}

Time Complexity

CaseTime ComplexityExplanation
Best CaseO(n)Even if the array starts with a long streak of 1s, we still need to check all elements to ensure it's the longest sequence.
Average CaseO(n)The algorithm goes through each element of the array once in a single pass, updating counters as needed.
Worst CaseO(n)In the worst case, such as alternating 1s and 0s, every element must still be processed to determine the maximum streak.

Space Complexity

O(1)

Explanation: The algorithm uses only two variables to keep track of the current and maximum count. No additional space is required.


Comments

💬 Please keep your comment relevant and respectful. Avoid spamming, offensive language, or posting promotional/backlink content.
All comments are subject to moderation before being published.


Loading comments...