⬅ Previous Topic
Find Missing Number in ArrayNext Topic ⮕
Find Kth Smallest Element⬅ Previous Topic
Find Missing Number in ArrayNext Topic ⮕
Find Kth Smallest ElementTopic Contents
You are given a binary array that consists only of 0
s and 1
s. 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
.
arr
that contains only 0
and 1
.max_count = 0
and current_count = 0
.1
, increment current_count
.0
, reset current_count
to 0.max_count
if current_count
is greater.max_count
.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))
Case | Time Complexity | Explanation |
---|---|---|
Best Case | O(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 Case | O(n) | The algorithm goes through each element of the array once in a single pass, updating counters as needed. |
Average Case | O(n) | In the worst case, such as alternating 1s and 0s, every element must still be processed to determine the maximum streak. |
O(1)
Explanation: The algorithm uses only two variables to keep track of the current and maximum count. No additional space is required.
⬅ Previous Topic
Find Missing Number in ArrayNext Topic ⮕
Find Kth Smallest ElementYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.