Count all disjoint pairs having absolute difference at least K from a given array | 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 ; Given arr [ ] ; Size of array ; Given difference K ; Function Call
function countPairsWithDiffK ( arr , N , K ) { var vis = new Array ( N ) ; vis . fill ( 0 ) ; var count = 0 ; for ( var i = 0 ; i < N ; i ++ ) { if ( vis [ i ] == 1 ) continue ; for ( var 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 ; } } } document . write ( count + " " ) ; } var arr = [ 1 , 3 , 3 , 5 ] ; var N = arr . length ; var K = 2 ; countPairsWithDiffK ( arr , N , K ) ;