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 ; Prvar the answer ; Given array arr ; Given difference K ; Size of the array ; Function call
function isValid ( arr , n , m , d ) { for ( i = 0 ; i < m ; i ++ ) { if ( Math . abs ( arr [ n - m + i ] - arr [ i ] ) < d ) { return 0 ; } } return 1 ; } function countPairs ( arr , N , K ) { var ans = 0 ; var left = 0 , right = N / 2 + 1 ; arr . sort ( ) ; while ( left < right ) { var mid = parseInt ( ( left + right ) / 2 ) ; if ( isValid ( arr , N , mid , K ) == 1 ) { ans = mid ; left = mid + 1 ; } else right = mid - 1 ; } document . write ( ans ) ; } var arr = [ 1 , 3 , 3 , 5 ] ; var K = 2 ; var N = arr . length ; countPairs ( arr , N , K ) ;