Longest subarray with difference exactly K between any two distinct values | Function to return the length of the longest sub - array ; Initialize set ; Store 1 st element of sub - array into set ; Check absolute difference between two elements ; If the new element is not present in the set ; If the set contains two elements ; Otherwise ; Update the maximum length ; Remove the set elements ; Driver Code
def longestSubarray ( arr , n , k ) : NEW_LINE INDENT Max = 1 NEW_LINE s = set ( ) NEW_LINE for i in range ( n - 1 ) : NEW_LINE INDENT s . add ( arr [ i ] ) NEW_LINE for j in range ( i + 1 , n ) : NEW_LINE INDENT if ( abs ( arr [ i ] - arr [ j ] ) == 0 or abs ( arr [ i ] - arr [ j ] ) == k ) : NEW_LINE INDENT if ( not arr [ j ] in s ) : NEW_LINE INDENT if ( len ( s ) == 2 ) : NEW_LINE INDENT break NEW_LINE DEDENT else : NEW_LINE INDENT s . add ( arr [ j ] ) NEW_LINE DEDENT DEDENT DEDENT else : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT if ( len ( s ) == 2 ) : NEW_LINE INDENT Max = max ( Max , j - i ) NEW_LINE s . clear ( ) NEW_LINE DEDENT else : NEW_LINE INDENT s . clear ( ) NEW_LINE DEDENT DEDENT return Max NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 0 , 2 , 2 , 5 , 5 , 5 ] NEW_LINE N = len ( arr ) NEW_LINE K = 1 NEW_LINE length = longestSubarray ( arr , N , K ) NEW_LINE if ( length == 1 ) : NEW_LINE INDENT print ( " - 1" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( length ) NEW_LINE DEDENT DEDENT