Given a binary array, find the maximum number of consecutive is in the array.
Example:
I/P: [1, 1, 0, 1, 1, 1]
O/P: 3
Explanation:
The first two digits or the last three digits are consecutive 1’s.
The maximum number of consecutive is 3.
The input array will only contain 0 and 1.
Explanation:
Here 1st consecutive 1’s is 2 and then 3
So, the maximum is 3
We will create a variable to count the current total consecutive 1’s, then we will compare the value with the last total come count of consecutive 1’s, we will return the maximum value.
For counting, we will use the concept of AND
0 AND 0 → 0
0 AND 1 → 0
1 AND 0 → 0
1 AND 1 → 1
We will AND 1 with each index value and check whether it is 1 and count 0 accordingly.
Algorithm
Step 1: Initialize 3 variables k, m, j as k = 1, m = 0, j = 0
Step 2: Run a loop in the length of nums
Step 3: AND k with each value of nums
Step 4: if the value and k == True i.e. 1
then increment j by 1
store the current max count to m
else
reset j to 0
Step 5: Run Step 2 to Step 4 until reach end of array
Step 6: Return m /Maximum Consecutive 1’s
Time Complexity: O(n) /length of nums = n
Space Complexity: O(1)