Maximum Consecutive Ones in an Array
- Shreyas Naphad
- Jun 5, 2024
- 1 min read
In this article, we will solve the problem of finding the maximum number of consecutive 1s in a binary array that contains only 0s and 1s.
Example:
Input: [1, 1, 0, 1, 1, 1]
Output: 3
Solution:
To solve this problem, we can iterate through the array while keeping track of the current streak of consecutive 1s and find the maximum streak encountered so far.
Steps to Solve:
1. Initialize Counters:
o Use two variables: currentCount to count the current streak of consecutive 1s, and maxCount to store the maximum streak till now.
2. Iterate Through Array:
o For each element in the array:
§ If the element is 1, increment currentCount.
§ If the element is 0, update maxCount if currentCount is greater, and reset currentCount to 0.
3. Final Check:
o After the loop, check if the last streak of 1s was the maximum by comparing currentCount with maxCount.
Time Complexity: O(N)
Space Complexity: O(1)
Comments