Longest Consecutive Subsequence | C # program to find longest consecutive subsequence ; Returns length of the longest consecutive subsequence ; Hash all the array elements ; 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 ; update optimal length if this length is more ; Driver code
public class ArrayElements { public static int findLongestConseqSubseq ( int [ ] arr , int n ) { HashSet < int > S = new HashSet < int > ( ) ; int ans = 0 ; for ( int i = 0 ; i < n ; ++ i ) { S . Add ( arr [ i ] ) ; } for ( int i = 0 ; i < n ; ++ i ) { if ( ! S . Contains ( arr [ i ] - 1 ) ) { int j = arr [ i ] ; while ( S . Contains ( j ) ) { j ++ ; } if ( ans < j - arr [ i ] ) { ans = j - arr [ i ] ; } } } return ans ; } public static void Main ( string [ ] args ) { int [ ] arr = new int [ ] { 1 , 9 , 3 , 10 , 4 , 20 , 2 } ; int n = arr . Length ; Console . WriteLine ( " Length ▁ of ▁ the ▁ Longest ▁ consecutive ▁ subsequence ▁ is ▁ " + findLongestConseqSubseq ( arr , n ) ) ; } }