Max Consecutive Ones in Array - Optimal Approach

Max Consecutive Ones in Array - Optimal Approach

Visualization

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.

Find Maximum Consecutive Ones in Binary Array Code

Python
JavaScript
Java
C++
C
def max_consecutive_ones(arr):
    max_count = 0
    current_count = 0
    for num in arr:
        if num == 1:
            current_count += 1
            max_count = max(max_count, current_count)
        else:
            current_count = 0
    return max_count

# Sample Input
arr = [1, 1, 0, 1, 1, 1]
print("Max Consecutive Ones:", max_consecutive_ones(arr))