Maximum consecutive numbers present in an array | C # 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
using System ; using System . Collections . Generic ; public class GFG { static int findLongestConseqSubseq ( int [ ] arr , int n ) { HashSet < int > S = new HashSet < int > ( ) ; for ( int i = 0 ; i < n ; i ++ ) S . Add ( arr [ i ] ) ; int ans = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( S . Contains ( arr [ i ] ) ) { int j = arr [ i ] ; while ( S . Contains ( j ) ) j ++ ; ans = Math . Max ( ans , j - arr [ i ] ) ; } } return ans ; } public static void Main ( String [ ] args ) { int [ ] arr = { 1 , 94 , 93 , 1000 , 5 , 92 , 78 } ; int n = arr . Length ; Console . WriteLine ( findLongestConseqSubseq ( arr , n ) ) ; } }