Count all disjoint pairs having absolute difference at least K from a given array | Java program for the above approach ; 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
import java . util . * ; class GFG { static int isValid ( int arr [ ] , int n , int m , int d ) { for ( int i = 0 ; i < m ; i ++ ) { if ( Math . abs ( arr [ n - m + i ] - arr [ i ] ) < d ) { return 0 ; } } return 1 ; } static void countPairs ( int arr [ ] , int N , int K ) { int ans = 0 ; int left = 0 , right = N / 2 + 1 ; Arrays . sort ( arr ) ; while ( left < right ) { int mid = ( left + right ) / 2 ; if ( isValid ( arr , N , mid , K ) == 1 ) { ans = mid ; left = mid + 1 ; } else right = mid - 1 ; } System . out . print ( ans ) ; } public static void main ( String args [ ] ) { int arr [ ] = { 1 , 3 , 3 , 5 } ; int K = 2 ; int N = arr . length ; countPairs ( arr , N , K ) ; } }