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
function longestSubarray ( arr , n , k ) { let i , j , Max = 1 ; let s = new Set ( ) ; for ( i = 0 ; i < n - 1 ; i ++ ) { s . add ( arr [ i ] ) ; for ( j = i + 1 ; j < n ; j ++ ) { if ( Math . abs ( arr [ i ] - arr [ j ] ) == 0 || Math . abs ( arr [ i ] - arr [ j ] ) == k ) { if ( ! s . has ( arr [ j ] ) ) { if ( s . size == 2 ) break ; else s . add ( arr [ j ] ) ; } } else break ; } if ( s . size == 2 ) { Max = Math . max ( Max , j - i ) ; s . clear ; } else s . clear ; } return Max ; } let arr = [ 1 , 0 , 2 , 2 , 5 , 5 , 5 ] ; let N = arr . length ; let K = 1 ; let length = longestSubarray ( arr , N , K ) ; if ( length == 1 ) document . write ( - 1 ) ; else document . write ( length ) ;