Algorithm Steps
- Given an array
arr
that contains only0
and1
. - Initialize two counters:
max_count = 0
andcurrent_count = 0
. - Iterate through the array:
- → If the current element is
1
, incrementcurrent_count
. - → If the current element is
0
, resetcurrent_count
to 0. - After each step, update
max_count
ifcurrent_count
is greater. - 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))