Count all disjoint pairs having absolute difference at least K from a given array | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; void countPairsWithDiffK ( int arr [ ] , int N , int K ) { int vis [ N ] ; memset ( vis , 0 , sizeof ( vis ) ) ; 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 ( abs ( arr [ i ] - arr [ j ] ) >= K ) { count ++ ; vis [ i ] = 1 ; vis [ j ] = 1 ; break ; } } } cout << count << ' ▁ ' ; } int main ( ) { int arr [ ] = { 1 , 3 , 3 , 5 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int K = 2 ; countPairsWithDiffK ( arr , N , K ) ; return 0 ; }