![]() |
VOOZH | about |
Given a binary array arr[] consisting of only 0s and 1s, find the length of the longest contiguous sequence of either 1s or 0s in the array.
Examples :
Input: arr[] = [0, 1, 0, 1, 1, 1, 1]
Output: 4
Explanation: The maximum number of consecutive 1’s in the array is 4 from index 3-6.Input: arr[] = [0, 0, 1, 0, 1, 0]
Output: 2
Explanation: The maximum number of consecutive 0’s in the array is 2 from index 0-1.Input: arr[] = [0, 0, 0, 0]
Output: 4
Explanation: The maximum number of consecutive 0’s in the array is 4.
Table of Content
The idea is to traverse the array once and count how many times the same value repeats consecutively. The thought process is to use a counter that increases when the current element matches the previous one. If a change is detected, we update the maximum streak and reset the count.
Steps-By-Step Approach:
4
The idea is to use XOR (^) to check if consecutive elements are the same. As XOR of two numbers is 0 if both numbers are same. So, If prev ^ num == 0, the sequence continues; else we update the maximum streak and reset the count.
Steps to implement the above idea:
4