To solve this problem, we need to count how many 1s appear consecutively in the array. Whenever we encounter a 0, we know the streak is broken and we reset our count.
Let’s break it down:
- We start scanning the array from the beginning.
- Each time we see a
1
, we increase a temporary counter (say current_count
).
- If we see a
0
, that means the current sequence has ended, so we reset current_count
to 0.
- Throughout the loop, we also keep track of the highest value
current_count
has reached — that’s our max_count
.
Let’s understand different scenarios:
- Normal case: If the array has both 1s and 0s, we look for the longest continuous stretch of 1s between 0s. For example, in
[1, 1, 0, 1, 1, 1]
, the answer is 3
.
- All 1s: If the array contains only 1s (like
[1, 1, 1, 1]
), then the entire array is one long stretch — the answer is the length of the array.
- All 0s: If the array contains only 0s, there are no 1s, so the answer is
0
.
- Isolated 1s: If every 1 is surrounded by 0s (like
[1, 0, 1]
), then the maximum stretch is just 1
.
- Empty array: If the array has no elements, then clearly there are no 1s to count — we return
0
.
This method uses a single loop and no extra space, making it extremely efficient. It works in O(n) time where n
is the number of elements in the array.