Understanding the Problem
We are given an array of binary numbers — that means it only contains 0
s and 1
s.
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.
Comments
Loading comments...