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
def countPairs ( arr , k ) : NEW_LINE INDENT arr . sort ( ) NEW_LINE pair = 0 NEW_LINE index = 0 NEW_LINE while ( index < len ( arr ) - 1 ) : NEW_LINE INDENT if arr [ index + 1 ] - arr [ index ] <= k : NEW_LINE INDENT pair += 1 NEW_LINE index += 2 NEW_LINE DEDENT else : NEW_LINE INDENT index += 1 NEW_LINE DEDENT DEDENT return pair NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 4 , 3 , 7 , 5 ] NEW_LINE k = 2 NEW_LINE count = countPairs ( arr , k ) NEW_LINE print ( count ) NEW_LINE DEDENT