Length of longest non | Java program for the above approach ; Function to find the longest non - decreasing subsequence with difference between adjacent elements exactly equal to 1 ; Base case ; Sort the array in ascending order ; Stores the maximum length ; Traverse the array ; If difference between current pair of adjacent elements is 1 or 0 ; Extend the current sequence Update len and max_len ; Otherwise , start a new subsequence ; Print the maximum length ; Driver Code ; Given array ; Size of the array ; Function call to find the longest subsequence
import java . io . * ; import java . util . * ; class GFG { static void longestSequence ( int arr [ ] , int N ) { if ( N == 0 ) { System . out . println ( 0 ) ; return ; } Arrays . sort ( arr ) ; int maxLen = 1 ; int len = 1 ; for ( int i = 1 ; i < N ; i ++ ) { if ( arr [ i ] == arr [ i - 1 ] arr [ i ] == arr [ i - 1 ] + 1 ) { len ++ ; maxLen = Math . max ( maxLen , len ) ; } else { len = 1 ; } } System . out . println ( maxLen ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 8 , 5 , 4 , 8 , 4 } ; int N = arr . length ; longestSequence ( arr , N ) ; } }