Count all disjoint pairs having absolute difference at least K from a given array | Java program for the above approach ; Function to count distinct pairs with absolute difference atleast K ; Track the element that have been paired ; Stores count of distinct pairs ; Pick all elements one by one ; If already visited ; If already visited ; If difference is at least K ; Mark element as visited and increment the count ; Print the final count ; Driver Code ; Given arr [ ] ; Size of array ; Given difference K ; Function Call
import java . util . * ; class GFG { static void countPairsWithDiffK ( int arr [ ] , int N , int K ) { int [ ] vis = new int [ N ] ; Arrays . fill ( vis , 0 ) ; int count = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( vis [ i ] == 1 ) continue ; for ( int j = i + 1 ; j < N ; j ++ ) { if ( vis [ j ] == 1 ) continue ; if ( Math . abs ( arr [ i ] - arr [ j ] ) >= K ) { count ++ ; vis [ i ] = 1 ; vis [ j ] = 1 ; break ; } } } System . out . print ( count ) ; } public static void main ( String args [ ] ) { int arr [ ] = { 1 , 3 , 3 , 5 } ; int N = arr . length ; int K = 2 ; countPairsWithDiffK ( arr , N , K ) ; } }