Count all disjoint pairs having absolute difference at least K from a given array | Function to check if it is possible to form M pairs with abs diff at least K ; Traverse the array over [ 0 , M ] ; If valid index ; Return 1 ; Function to count distinct pairs with absolute difference atleasr K ; Stores the count of all possible pairs ; Initialize left and right ; Sort the array ; Perform Binary Search ; Find the value of mid ; Check valid index ; Update ans ; Print the answer ; Driver Code ; Given array arr [ ] ; Given difference K ; Size of the array ; Function call
def isValid ( arr , n , m , d ) : NEW_LINE INDENT for i in range ( m ) : NEW_LINE INDENT if ( abs ( arr [ n - m + i ] - arr [ i ] ) < d ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT DEDENT return 1 NEW_LINE DEDENT def countPairs ( arr , N , K ) : NEW_LINE INDENT ans = 0 NEW_LINE left = 0 NEW_LINE right = N // 2 + 1 NEW_LINE arr . sort ( reverse = False ) NEW_LINE while ( left < right ) : NEW_LINE INDENT mid = ( left + right ) // 2 NEW_LINE if ( isValid ( arr , N , mid , K ) ) : NEW_LINE INDENT ans = mid NEW_LINE left = mid + 1 NEW_LINE DEDENT else : NEW_LINE INDENT right = mid - 1 NEW_LINE DEDENT DEDENT print ( ans , end = " " ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 3 , 3 , 5 ] NEW_LINE K = 2 NEW_LINE N = len ( arr ) NEW_LINE countPairs ( arr , N , K ) NEW_LINE DEDENT