Maximum consecutive numbers present in an array | CPP program to find largest consecutive numbers present in arr [ ] . ; We insert all the array elements into unordered set . ; check each possible sequence from the start then update optimal length ; if current element is the starting element of a sequence ; Then check for next elements in the sequence ; increment the value of array element and repeat search in the set ; Update optimal length if this length is more . To get the length as it is incremented one by one ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findLongestConseqSubseq ( int arr [ ] , int n ) { unordered_set < int > S ; for ( int i = 0 ; i < n ; i ++ ) S . insert ( arr [ i ] ) ; int ans = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( S . find ( arr [ i ] - 1 ) == S . end ( ) ) { int j = arr [ i ] ; while ( S . find ( j ) != S . end ( ) ) j ++ ; ans = max ( ans , j - arr [ i ] ) ; } } return ans ; } int main ( ) { int arr [ ] = { 1 , 94 , 93 , 1000 , 5 , 92 , 78 } ; int n = sizeof ( arr ) / sizeof ( int ) ; cout << findLongestConseqSubseq ( arr , n ) << endl ; return 0 ; }