Longest Consecutive Subsequence | Java Program to find longest consecutive subsequence This Program uses Priority Queue ; return the length of the longest subsequence of consecutive integers ; adding element from array to PriorityQueue ; Storing the first element of the Priority Queue This first element is also the smallest element ; Taking a counter variable with value 1 ; Storing value of max as 1 as there will always be one element ; check if current peek element minus previous element is greater then 1 This is done because if it ' s ▁ greater ▁ than ▁ 1 ▁ ▁ then ▁ the ▁ sequence ▁ ▁ doesn ' t start or is broken here ; Store the value of counter to 1 As new sequence may begin ; Update the previous position with the current peek And remove it ; Check if the previous element and peek are same ; Update the previous position with the current peek And remove it ; if the difference between previous element and peek is 1 ; Update the counter These are consecutive elements ; Update the previous position with the current peek And remove it ; Check if current longest subsequence is the greatest ; Store the current subsequence count as max ; Driver Code
import java . io . * ; import java . util . PriorityQueue ; public class Longset_Sub { static int findLongestConseqSubseq ( int arr [ ] , int N ) { PriorityQueue < Integer > pq = new PriorityQueue < Integer > ( ) ; for ( int i = 0 ; i < N ; i ++ ) { pq . add ( arr [ i ] ) ; } int prev = pq . poll ( ) ; int c = 1 ; int max = 1 ; for ( int i = 1 ; i < N ; i ++ ) { if ( pq . peek ( ) - prev > 1 ) { c = 1 ; prev = pq . poll ( ) ; } else if ( pq . peek ( ) - prev == 0 ) { prev = pq . poll ( ) ; } else { c ++ ; prev = pq . poll ( ) ; } if ( max < c ) { max = c ; } } return max ; } public static void main ( String args [ ] ) throws IOException { int arr [ ] = { 1 , 9 , 3 , 10 , 4 , 20 , 2 } ; int n = arr . length ; System . out . println ( " Length ▁ of ▁ the ▁ Longest ▁ consecutive ▁ subsequence ▁ is ▁ " + findLongestConseqSubseq ( arr , n ) ) ; } }