Given binary array, find count of maximum number of consecutive 1’s present in the array.
Examples :
Input : arr[] = {1, 1, 0, 0, 1, 0, 1, 0, 1, 1, 1, 1}
Output : 4
Input : arr[] = {0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1}
Output : 1
A simple solution is consider every subarray and count 1’s in every subarray. Finally return size of largest subarray with all 1’s. An efficient solution is traverse array from left to right. If we see a 1, we increment count and compare it with maximum so far. If we see a 0, we reset count as 0.
Implementation:
// C++ program to count maximum consecutive // 1's in a binary array. #include<bits/stdc++.h> using namespace std;
// Returns count of maximum consecutive 1's // in binary array arr[0..n-1] int getMaxLength( bool arr[], int n)
{ int count = 0; //initialize count
int result = 0; //initialize max
for ( int i = 0; i < n; i++)
{
// Reset count when 0 is found
if (arr[i] == 0)
count = 0;
// If 1 is found, increment count
// and update result if count becomes
// more.
else
{
count++; //increase count
result = max(result, count);
}
}
return result;
} // Driver code int main()
{ bool arr[] = {1, 1, 0, 0, 1, 0, 1, 0,
1, 1, 1, 1};
int n = sizeof (arr)/ sizeof (arr[0]);
cout << getMaxLength(arr, n) << endl;
return 0;
} |
// Java program to count maximum consecutive // 1's in a binary array. class GFG {
// Returns count of maximum consecutive 1's
// in binary array arr[0..n-1]
static int getMaxLength( boolean arr[], int n)
{
int count = 0 ; //initialize count
int result = 0 ; //initialize max
for ( int i = 0 ; i < n; i++)
{
// Reset count when 0 is found
if (arr[i] == false )
count = 0 ;
// If 1 is found, increment count
// and update result if count becomes
// more.
else
{
count++; //increase count
result = Math.max(result, count);
}
}
return result;
}
// Driver method
public static void main(String[] args)
{
boolean arr[] = { true , true , false , false ,
true , false , true , false ,
true , true , true , true };
int n = arr.length;
System.out.println(getMaxLength(arr, n));
}
} // This code is contributed by Anant Agarwal. |
# Python 3 program to count # maximum consecutive 1's # in a binary array. # Returns count of maximum # consecutive 1's in binary # array arr[0..n-1] def getMaxLength(arr, n):
# initialize count
count = 0
# initialize max
result = 0
for i in range ( 0 , n):
# Reset count when 0 is found
if (arr[i] = = 0 ):
count = 0
# If 1 is found, increment count
# and update result if count
# becomes more.
else :
# increase count
count + = 1
result = max (result, count)
return result
# Driver code arr = [ 1 , 1 , 0 , 0 , 1 , 0 , 1 ,
0 , 1 , 1 , 1 , 1 ]
n = len (arr)
print (getMaxLength(arr, n))
# This code is contributed by Smitha Dinesh Semwal |
// C# program to count maximum // consecutive 1's in a binary array. using System;
class GFG {
// Returns count of maximum consecutive
// 1's in binary array arr[0..n-1]
static int getMaxLength( bool []arr, int n)
{
int count = 0; //initialize count
int result = 0; //initialize max
for ( int i = 0; i < n; i++)
{
// Reset count when 0 is found
if (arr[i] == false )
count = 0;
// If 1 is found, increment count
// and update result if count
// becomes more.
else
{
count++; //increase count
result = Math.Max(result, count);
}
}
return result;
}
// Driver code
public static void Main()
{
bool []arr = { true , true , false , false ,
true , false , true , false ,
true , true , true , true };
int n = arr.Length;
Console.Write(getMaxLength(arr, n));
}
} // This code is contributed by Nitin Mittal. |
<script> // JavaScript program to count maximum // consecutive 1's in a binary array. // Returns count of maximum // consecutive 1's in binary // array arr[0..n-1] function getMaxLength(arr, n) {
// initialize count
let count = 0;
// initialize max
let result = 0;
for (let i = 0; i < n; i++) {
// Reset count when 0 is found
if (arr[i] == 0)
count = 0;
// If 1 is found, increment
// count and update result
// if count becomes more.
else {
// increase count
count++;
result = Math.max(result, count);
}
}
return result;
} // Driver code let arr = new Array(1, 1, 0, 0, 1, 0,
1, 0, 1, 1, 1, 1);
let n = arr.length; document.write(getMaxLength(arr, n)); // This code is contributed by gfgking </script> |
<?php // PHP program to count maximum // consecutive 1's in a binary array. // Returns count of maximum // consecutive 1's in binary // array arr[0..n-1] function getMaxLength( $arr , $n )
{ // initialize count
$count = 0;
// initialize max
$result = 0;
for ( $i = 0; $i < $n ; $i ++)
{
// Reset count when 0 is found
if ( $arr [ $i ] == 0)
$count = 0;
// If 1 is found, increment
// count and update result
// if count becomes more.
else
{
// increase count
$count ++;
$result = max( $result , $count );
}
}
return $result ;
} // Driver code $arr = array (1, 1, 0, 0, 1, 0,
1, 0, 1, 1, 1, 1);
$n = sizeof( $arr ) / sizeof( $arr [0]);
echo getMaxLength( $arr , $n ) ;
// This code is contributed by nitin mittal. ?> |
4
Time Complexity : O(n)
Auxiliary Space : O(1)
Approach 2:
Another approach to solve this problem is to use the bitwise AND operation to count the number of consecutive 1’s in the binary representation of the given number. We iterate over the bits of the number from the right and use a mask to check the value of each bit. If the bit is 1, we increment a counter. If the bit is 0, we reset the counter to zero. We update the maxCount if the counter is greater than maxCount.
Here’s the implementation of the above approach in C++:
#include <iostream> #include <vector> using namespace std;
int maxConsecutiveOnes(vector< int >& nums) {
int max_count = 0, current_count = 0, mask = 0;
for ( int i = 0; i < nums.size(); i++) {
if (nums[i] == 1) {
mask = (mask << 1) | 1;
} else {
mask = mask << 1;
}
if ((nums[i] & mask) != 0) {
current_count++;
} else {
max_count = max(max_count, current_count);
current_count = 0;
mask = 0;
}
}
max_count = max(max_count, current_count);
return max_count;
} int main() {
vector< int > nums = {1, 1, 0, 0, 1, 0, 1, 0,
1, 1, 1, 1};
int max_ones = maxConsecutiveOnes(nums);
cout << "Maximum consecutive ones: " << max_ones << endl;
return 0;
} |
import java.util.ArrayList;
public class Main {
// Function to find the maximum consecutive ones in an ArrayList of integers
public static int maxConsecutiveOnes(ArrayList<Integer> nums) {
int maxCount = 0 ; // Initialize the maximum count to zero
int currentCount = 0 ; // Initialize the current count to zero
int mask = 0 ; // Initialize a bit mask to keep track of consecutive ones
// Iterate through the ArrayList
for ( int i = 0 ; i < nums.size(); i++) {
// If the current element is 1, update the mask to include this one
if (nums.get(i) == 1 ) {
mask = (mask << 1 ) | 1 ;
} else {
// If the current element is not 1, shift the mask left (no longer consecutive ones)
mask = mask << 1 ;
}
// Check if the bitwise AND of the current element and the mask is not zero
if ((nums.get(i) & mask) != 0 ) {
currentCount++; // Increment the current count for consecutive ones
} else {
// If consecutive ones are interrupted, update the maximum count if necessary
maxCount = Math.max(maxCount, currentCount);
currentCount = 0 ; // Reset the current count
mask = 0 ; // Reset the mask
}
}
// Update the maximum count one more time in case the sequence ends with consecutive ones
maxCount = Math.max(maxCount, currentCount);
return maxCount;
}
public static void main(String[] args) {
ArrayList<Integer> nums = new ArrayList<>();
nums.add( 1 );
nums.add( 1 );
nums.add( 0 );
nums.add( 0 );
nums.add( 1 );
nums.add( 0 );
nums.add( 1 );
nums.add( 0 );
nums.add( 1 );
nums.add( 1 );
nums.add( 1 );
nums.add( 1 );
int maxOnes = maxConsecutiveOnes(nums);
System.out.println( "Maximum consecutive ones: " + maxOnes);
}
} |
# Function to find the maximum number of consecutive ones in a binary array def max_consecutive_ones(nums):
max_count = 0 # Initialize the maximum consecutive ones count to 0
current_count = 0 # Initialize the current consecutive ones count to 0
mask = 0 # Initialize a mask to keep track of consecutive ones
for num in nums: # Iterate through the elements in the array
if num = = 1 :
mask = (mask << 1 ) | 1 # Shift the mask one position left and set the rightmost bit to 1
else :
mask = mask << 1 # Shift the mask one position left (rightmost bit becomes 0)
if (num & mask) ! = 0 : # Check if the bitwise AND of the current element
# and the mask is not 0
current_count + = 1 # If there is a consecutive one, increment the current count
else :
max_count = max (max_count, current_count) # Update the maximum count if necessary
current_count = 0 # Reset the current count to 0
mask = 0 # Reset the mask to 0
max_count = max (max_count, current_count) # Update the maximum count after the loop
return max_count
# Main function def main():
nums = [ 1 , 1 , 0 , 0 , 1 , 0 , 1 , 0 , 1 , 1 , 1 , 1 ]
max_ones = max_consecutive_ones(nums) # Find the maximum consecutive ones
print ( "Maximum consecutive ones:" , max_ones)
if __name__ = = "__main__" :
main()
|
using System;
using System.Collections.Generic;
class Program
{ // Function to find the maximum consecutive ones in a List of integers
static int MaxConsecutiveOnes(List< int > nums)
{
int maxCount = 0; // Initialize the maximum count to zero
int currentCount = 0; // Initialize the current count to zero
int mask = 0; // Initialize a bit mask to keep track of consecutive ones
// Iterate through the List
for ( int i = 0; i < nums.Count; i++)
{
// If the current element is 1, update the mask to include this one
if (nums[i] == 1)
{
mask = (mask << 1) | 1;
}
else
{
// If the current element is not 1, shift the mask
// left (no longer consecutive ones)
mask = mask << 1;
}
// Check if the bitwise AND of the current element and the mask is not zero
if ((nums[i] & mask) != 0)
{
currentCount++; // Increment the current count for consecutive ones
}
else
{
// If consecutive ones are interrupted, update the maximum count if necessary
maxCount = Math.Max(maxCount, currentCount);
currentCount = 0; // Reset the current count
mask = 0; // Reset the mask
}
}
// Update the maximum count one more time in case the sequence ends with consecutive ones
maxCount = Math.Max(maxCount, currentCount);
return maxCount;
}
static void Main()
{
List< int > nums = new List< int > { 1, 1, 0, 0, 1, 0, 1, 0, 1, 1, 1, 1 };
int maxOnes = MaxConsecutiveOnes(nums);
Console.WriteLine( "Maximum consecutive ones: " + maxOnes);
}
} |
// Function to find the maximum consecutive ones in an array function maxConsecutiveOnes(nums) {
let maxCount = 0, currentCount = 0, mask = 0;
for (let i = 0; i < nums.length; i++) {
// Update the mask to represent the current sequence of consecutive ones
if (nums[i] === 1) {
mask = (mask << 1) | 1;
} else {
mask = mask << 1;
}
// Check if the current element contributes to consecutive ones
if ((nums[i] & mask) !== 0) {
currentCount++;
} else {
// Update the maximum count and reset the current count if consecutive sequence ends
maxCount = Math.max(maxCount, currentCount);
currentCount = 0;
mask = 0; // Reset the mask for the next potential sequence
}
}
// Update the maximum count considering the last sequence
maxCount = Math.max(maxCount, currentCount);
return maxCount;
} // Driver program const nums = [1, 1, 0, 0, 1, 0, 1, 0, 1, 1, 1, 1]; const maxOnes = maxConsecutiveOnes(nums); // Print the result console.log( "Maximum consecutive ones:" , maxOnes);
|
Maximum consecutive ones: 4
Time Complexity: O(logn), where n is the decimal representation of the given number.
Space Complexity: O(1).
Exercise:
Maximum consecutive zeros in a binary array.
This article is contributed by Smarak Chopdar.