Maximum consecutive one’s (or zeros) in a binary circular array in C++

We are given with a circular array. Circular array is the array for which we consider the case that the first element comes next to the last element. It is used to implement queues. So we have to count the maximum no. of consecutive 1’s or 0’s in that array.

Let’s understand with examples.

Input − Arr[] = { 1,1,0,1,0,1,0,1,1,1 }

Output − Maximum consecutive 1’s are 5. Or Maximum consecutive 0’s is 1.

Explanation − From Arr[] index 7 to 9 and then indexes 0 and 1. 1’s are 5. No consecutive 0’s but 1.

Input − Arr[] = { 0,0,0,1,0 }

Output − Maximum consecutive 1’s is1. Or Maximum consecutive 0’s are 4.

Explanation − From Arr[] index 4 and then indexes 0 to 3. 0’s are 4.

Approach used in the below program is as follows

  • We take an input Arr[] which contains 0’s and 1’s in random order.

  • Variable N is used for the size of the Arr[].

  • Bit is used to store the 1 or 0, according to which we will count.

  • Function maxConsecutive(int arr[], int n, int bit) takes three input parameters. The array itself, its size and 0 or 1 as bit. Returns the count of bits past.

  • To make the array circular. Temp[2*n] is used to store the arr[] twice in it. While() loop runs twice to copy arr[] into temp.

  • Now we will count consecutive 1’s ( or 0’s ) using while ( temp[k++]==bit ) and store consecutive count in variable ‘count’.

  • If this count is maximum found so far, store it in maxC.

  • Return the maxC as a final result.


 Live Demo

#include <iostream>
//to return maximum bishops possible
int maxConsecutive(int arr[],int n,int bit){
   int count=0;
   int temp[2*n]={0};
   int maxC=0;
   int j=0,k=0; //to twice copy arr[]
      for(int i=0;i<n;i++){
   for(int i=0;i<2*n; i++){
   return maxC;
int main(){
   int Arr[]={1, 1, 0, 0, 1, 0, 1, 0, 1, 1, 1, 1 };
   int N = 12;
   int bit=1;
   printf("Maximum Consecutive 1's in circular array: %d",maxConsecutive(Arr,N,bit));
   printf("\nMaximum Consecutive 0's in circular array: %d",maxConsecutive(Arr,N,bit));
   return 0;


If we run the above code it will generate the following output −

Maximum Consecutive 1's in circular array: 6
Maximum Consecutive 0's in circular array: 2