ProgramGuru

Find Maximum Consecutive Ones in a Binary Array

Problem and examples

Given a binary array nums (containing only 0s and 1s), your task is to find the maximum number of consecutive 1s in the array.

If the array is empty, return 0.

Example:

Input: nums = [1,1,0,1,1,1] → Output: 3

Explanation: The longest run of consecutive 1s is from index 3 to 5.

nums Output Description
[1, 1, 0, 1, 1, 1] 3 Longest streak of 1s is from index 3 to 5: [1, 1, 1]
[1, 1, 1, 1] 4 All elements are 1s, entire array is the streak
[0, 0, 0] 0 No 1s present, so maximum consecutive 1s is 0
[1, 0, 1, 0, 1] 1 No consecutive 1s; each 1 is isolated
[0, 1, 1, 1, 0, 1, 1] 3 Two runs of 1s; longest one is of length 3 from index 1 to 3
[1] 1 Single element 1 forms a run of length 1
[0] 0 Single 0, so no 1s found
[] 0 Empty input array, so return 0 as per definition

Explore Max Consecutive Ones - Sliding Window

Load an example or enter your own input. Use the player controls to follow each change.

Understanding the Problem

We are given an array of binary numbers — that means it only contains 0s and 1s.

Our task is to find the maximum number of consecutive 1s in the array. That means we need to scan the array and figure out the longest stretch where all the numbers are 1 and appear one after the other, without a 0 in between.

This is a perfect scenario to use the sliding window technique — a powerful method to scan parts of an array while maintaining some conditions (in this case, counting continuous 1s).

Step-by-Step Solution with Example

Step 1: Choose an Example

Let’s take the given example: nums = [1, 1, 0, 1, 1, 1]

We want to find the longest sequence of 1s without interruption. From looking at the array, we can see the longest streak is from index 3 to 5: [1, 1, 1], which is of length 3.

Step 2: Understand the Intuition

Imagine scanning the array with your eyes. Every time you see a 1, you continue counting. But the moment you see a 0, the count breaks, and you start over from the next number. This is the core idea behind using a sliding window.

Step 3: Initialize Variables

  • start = 0: This will mark the beginning of the current window of 1s.
  • end = 0: This will iterate through each element.
  • maxCount = 0: This keeps track of the maximum number of 1s seen so far.

Step 4: Traverse the Array

Loop until end reaches the end of the array. For each number:

  • If it is 1, that means the window is valid. Move end++.
  • If it is 0, the window breaks. Move both start and end to the next index after the zero to begin a fresh window.

At each step, update the result with maxCount = max(maxCount, end - start).

Step 5: Simulate on the Example

Array: [1, 1, 0, 1, 1, 1]

Index 0: nums[0] = 1 → window = [0-0] → length = 1 → maxCount = 1  
Index 1: nums[1] = 1 → window = [0-1] → length = 2 → maxCount = 2  
Index 2: nums[2] = 0 → break window → start = 3, end = 3  
Index 3: nums[3] = 1 → window = [3-3] → length = 1 → maxCount = 2  
Index 4: nums[4] = 1 → window = [3-4] → length = 2 → maxCount = 2  
Index 5: nums[5] = 1 → window = [3-5] → length = 3 → maxCount = 3  

Step 6: Return the Result

After the loop ends, the value of maxCount is 3, which is the correct answer.

Edge Cases

  • Empty Array: If nums = [], then return 0 since there are no elements.
  • No 1s: If nums = [0, 0, 0], then the longest sequence is 0.
  • All 1s: If nums = [1, 1, 1, 1], then return the length of the array, which is 4.
  • Single Element: If nums = [1], return 1. If nums = [0], return 0.

Final Thoughts

This problem teaches you how to use a simple sliding window approach to track continuous patterns in an array. By carefully updating your start and end pointers, and maintaining a count of maximum window size, you can solve this efficiently in O(n) time without using any extra space.

Always begin by understanding the problem and walking through an example manually. That helps you build intuition, especially for edge cases.

  1. Initialize two pointers: start = 0 and end = 0, and a variable maxCount = 0 to track the maximum streak of 1s.
  2. Loop while end is less than the length of the array:
  3. → If nums[end] == 1, the current window is valid, so continue expanding the window by doing end++.
  4. → If nums[end] == 0, reset the window: move start = end + 1 and increment end.
  5. → At each step, update maxCount = max(maxCount, end - start).
  6. Once the loop finishes, return maxCount as the result.

Implementation and efficiency

C implementation

#include <stdio.h>

int findMaxConsecutiveOnes(int* nums, int numsSize) {
    int maxCount = 0, start = 0, end = 0;
    while (end < numsSize) {
        if (nums[end] == 1) {
            end++;
        } else {
            start = end + 1;
            end++;
        }
        if (end - start > maxCount) {
            maxCount = end - start;
        }
    }
    return maxCount;
}

int main() {
    int nums[] = {1,1,0,1,1,1};
    int size = sizeof(nums)/sizeof(nums[0]);
    int result = findMaxConsecutiveOnes(nums, size);
    printf("Max consecutive ones: %d\n", result);
    return 0;
}

C++ implementation

#include <iostream>
#include <vector>
using namespace std;

int findMaxConsecutiveOnes(const vector<int>& nums) {
    int maxCount = 0, start = 0, end = 0;
    int n = nums.size();
    while (end < n) {
        if (nums[end] == 1) {
            end++;
        } else {
            start = end + 1;
            end++;
        }
        maxCount = max(maxCount, end - start);
    }
    return maxCount;
}

int main() {
    vector<int> nums = {1,1,0,1,1,1};
    cout << "Max consecutive ones: " << findMaxConsecutiveOnes(nums) << endl;
    return 0;
}

Python implementation

def find_max_consecutive_ones(nums):
    max_count = 0
    start = 0
    end = 0
    n = len(nums)
    while end < n:
        if nums[end] == 1:
            end += 1
        else:
            start = end + 1
            end += 1
        max_count = max(max_count, end - start)
    return max_count

# Example usage
nums = [1,1,0,1,1,1]
print(f"Max consecutive ones: {find_max_consecutive_ones(nums)}")

Java implementation

public class MaxConsecutiveOnes {
    public static int findMaxConsecutiveOnes(int[] nums) {
        int maxCount = 0, start = 0, end = 0;
        int n = nums.length;
        while (end < n) {
            if (nums[end] == 1) {
                end++;
            } else {
                start = end + 1;
                end++;
            }
            maxCount = Math.max(maxCount, end - start);
        }
        return maxCount;
    }

    public static void main(String[] args) {
        int[] nums = {1, 1, 0, 1, 1, 1};
        System.out.println("Max consecutive ones: " + findMaxConsecutiveOnes(nums));
    }
}

JavaScript implementation

function findMaxConsecutiveOnes(nums) {
  let maxCount = 0, start = 0, end = 0;
  while (end < nums.length) {
    if (nums[end] === 1) {
      end++;
    } else {
      start = end + 1;
      end++;
    }
    maxCount = Math.max(maxCount, end - start);
  }
  return maxCount;
}

const nums = [1,1,0,1,1,1];
console.log("Max consecutive ones:", findMaxConsecutiveOnes(nums));

Go implementation

package main

import "fmt"

func findMaxConsecutiveOnes(nums []int) int {
    maxCount, start, end := 0, 0, 0
    n := len(nums)
    for end < n {
        if nums[end] == 1 {
            end++
        } else {
            start = end + 1
            end++
        }
        if end - start > maxCount {
            maxCount = end - start
        }
    }
    return maxCount
}

func main() {
    nums := []int{1, 1, 0, 1, 1, 1}
    fmt.Printf("Max consecutive ones: %d\n", findMaxConsecutiveOnes(nums))
}

Rust implementation

fn find_max_consecutive_ones(nums: &[i32]) -> i32 {
    let mut max_count = 0;
    let mut start = 0;
    let mut end = 0;
    while end < nums.len() {
        if nums[end] == 1 {
            end += 1;
        } else {
            start = end + 1;
            end += 1;
        }
        max_count = max_count.max((end - start) as i32);
    }
    max_count
}

fn main() {
    let nums = [1,1,0,1,1,1];
    println!("Max consecutive ones: {}", find_max_consecutive_ones(&nums));
}

Kotlin implementation

fun findMaxConsecutiveOnes(nums: IntArray): Int {
    var maxCount = 0
    var start = 0
    var end = 0
    while (end < nums.size) {
        if (nums[end] == 1) {
            end++
        } else {
            start = end + 1
            end++
        }
        maxCount = maxOf(maxCount, end - start)
    }
    return maxCount
}

fun main() {
    val nums = intArrayOf(1,1,0,1,1,1)
    println("Max consecutive ones: ${findMaxConsecutiveOnes(nums)}")
}

Swift implementation

func findMaxConsecutiveOnes(_ nums: [Int]) -> Int {
    var maxCount = 0
    var start = 0
    var end = 0
    while end < nums.count {
        if nums[end] == 1 {
            end += 1
        } else {
            start = end + 1
            end += 1
        }
        maxCount = max(maxCount, end - start)
    }
    return maxCount
}

let nums = [1,1,0,1,1,1]
print("Max consecutive ones: \(findMaxConsecutiveOnes(nums))")

TypeScript implementation

function findMaxConsecutiveOnes(nums: number[]): number {
  let maxCount = 0, start = 0, end = 0;
  while (end < nums.length) {
    if (nums[end] === 1) {
      end++;
    } else {
      start = end + 1;
      end++;
    }
    maxCount = Math.max(maxCount, end - start);
  }
  return maxCount;
}

const nums = [1,1,0,1,1,1];
console.log("Max consecutive ones:", findMaxConsecutiveOnes(nums));

Time complexity

CaseTimeExplanation
best caseO(n)Even in the best case, such as when all elements are 1s, the algorithm must still iterate through the entire array to count them. Thus, the time complexity is linear.
average caseO(n)The algorithm uses a single pass through the array with two pointers. Each element is checked exactly once, so the operations grow linearly with the array size.
worst caseO(n)In the worst case, where 0s interrupt sequences of 1s frequently, the algorithm still performs a single pass through the array, yielding linear time complexity.

Space complexity

O(1)

The algorithm only uses a constant amount of extra space for pointers and counters (start, end, maxCount), regardless of the input size.