Length of longest non | 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
def longestSequence ( arr , N ) : NEW_LINE INDENT if ( N == 0 ) : NEW_LINE INDENT print ( 0 ) ; NEW_LINE return ; NEW_LINE DEDENT arr . sort ( ) ; NEW_LINE maxLen = 1 ; NEW_LINE len = 1 ; NEW_LINE for i in range ( 1 , N ) : NEW_LINE INDENT if ( arr [ i ] == arr [ i - 1 ] or arr [ i ] == arr [ i - 1 ] + 1 ) : NEW_LINE INDENT len += 1 ; NEW_LINE maxLen = max ( maxLen , len ) ; NEW_LINE DEDENT else : NEW_LINE INDENT len = 1 ; NEW_LINE DEDENT DEDENT print ( maxLen ) ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 8 , 5 , 4 , 8 , 4 ] ; NEW_LINE N = len ( arr ) ; NEW_LINE longestSequence ( arr , N ) ; NEW_LINE DEDENT