Maximum consecutive numbers present in an array in C++


We are given with an array of positive integers. The goal is to find the maximum number of consecutive numbers present in it. First of all we will sort the array and then compare adjacent elements arr[j]==arr[i]+1 (j=i+1), if difference is 1 then increment count and indexes i++,j++ else change count=1. Store the maximum count found so far stored in maxc.

Input

Arr[]= { 100,21,24,73,22,23 }

Output

Maximum consecutive numbers in array : 4

Explanation − Sorted array is − { 21,22,23,24,73,100 } initialize count=1,maxcount=1

1. 22=21+1 count=2 maxcount=2 i++,j++
2. 23=22+2 count=3 maxcount=3 i++,j++
3. 24=23+1 count=4 maxcount=4 i++,j++
4. 73=24+1 X count=1 maxcount=4 i++,j++
5. 100=73+1 X count=1 maxcount=4 i++,j++

Maximum consecutive numbers is 4 { 21,22,23,24 }

Input

Arr[]= { 11,41,21,42,61,43,9,44 }

Output

Maximum consecutive numbers in array : 4

Explanation − Sorted array is − { 9,11,21,41,42,43,44,61 } initialize count=1,maxcount=1

1. 11=9+1 X count=1 maxcount=1 i++,j++
2. 21=11+1 X count=1 maxcount=1 i++,j++
3. 41=21+1 X count=1 maxcount=1 i++,j++
4. 42=41+1 count=2 maxcount=2 i++,j++
5. 43=42+1 count=3 maxcount=3 i++,j++
6. 44=43+1 count=4 maxcount=4 i++,j++
7. 61=44+1 X count=1 maxcount=4 i++,j++

Maximum consecutive numbers is 4 { 41,42,43,44 }

Approach used in the below program is as follows

  • The integer array Arr[] is used to store the integers.

  • Integer ‘n’ stores the length of the array.

  • Function subs( int arr[], int n) takes an array , its size as input and returns the maximum consecutive numbers present in the array.

  • First of all we will sort the array using sort(arr,arr+n)

  • Now initialize the count=1 and maxc=1.

  • Starting from the first two elements, arr[0] and arr[1] inside two for loops, compare if arr[j]==arr[i]+1 ( j=i+1), if true then increment count and i by 1.

  • If the above condition is false again change count to 1. Update maxc with highest count found so far ( maxc=count>maxc?count:maxc ).

  • In the end return maxc as number of maximum consecutive elements as result.

Example

 Live Demo

#include <iostream>
#include <algorithm>
using namespace std;
int subs(int arr[],int n){
   std::sort(arr,arr+n);
   int count=1;
   int maxc=1;
   for(int i=0;i<n-1;i++){
      for(int j=i+1;j<n;j++){
         if(arr[j]==arr[i]+1){
             count++;
            i++;
         }
         else
            count=1;
         maxc=count>maxc?count:maxc;
      }
   }
   return maxc;
}
int main(){
   int arr[] = { 10,9,8,7,3,2,1,4,5,6 };
   int n = sizeof(arr) / sizeof(int);
   cout << "Maximum consecutive numbers present in an array :"<<subs(arr, n);
   return 0;
}

Output

Maximum consecutive numbers present in an array : 10

Updated on: 28-Jul-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements