Problem Description
Given a binary array, return the maximum number of consecutive 1's in the array.
Key Insights
- Iterate over the array while keeping track of the current sequence length of 1's.
- Reset the counter when a 0 is encountered.
- Update the maximum value during the iteration.
- This direct scanning results in a simple O(n) solution with constant space.
Space and Time Complexity
Time Complexity: O(n) - We traverse the array once. Space Complexity: O(1) - Only constant extra variables are used.
Solution
We iterate through the binary array and maintain two counters: one for the current sequence of consecutive 1's (currentCount) and one for the maximum sequence found so far (maxConsecutive). As we scan the array, we increment currentCount when we see a 1 and update maxConsecutive. When a 0 is found, we reset currentCount to 0. This approach leverages a simple linear pass through the array and uses a constant amount of extra space.