Count of pairs with difference at most K with no element repeating | Function to count the number of pairs whose difference is atmost K in an array ; Sorting the Array ; Variable to store the count of pairs whose difference is atmost K ; Loop to consider the consecutive pairs of the array ; if Pair found increment the index by 2 ; Driver Code ; Function Call
function countPairs ( arr , k , n ) { arr . sort ( ( a , b ) => a - b ) ; let pair = 0 ; let index = 0 ; while ( index < n - 1 ) { if ( arr [ index + 1 ] - arr [ index ] <= k ) { pair += 1 ; index += 2 ; } else { index += 1 ; } } return pair ; } let arr = [ 1 , 4 , 3 , 7 , 5 ] ; let k = 2 ; let n = arr . length ; let count = countPairs ( arr , k , n ) ; document . write ( count + " " ) ;