Longest Consecutive Subsequence | C ++ program to find longest contiguous subsequence ; Returns length of the longest contiguous 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findLongestConseqSubseq ( int arr [ ] , int n ) { unordered_set < int > S ; int ans = 0 ; for ( int i = 0 ; i < n ; i ++ ) S . insert ( arr [ i ] ) ; 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 , 9 , 3 , 10 , 4 , 20 , 2 } ; int n = sizeof arr / sizeof arr [ 0 ] ; cout << " Length ▁ of ▁ the ▁ Longest ▁ contiguous ▁ subsequence ▁ " " is ▁ " << findLongestConseqSubseq ( arr , n ) ; return 0 ; }