Count of pairs with difference at most K with no element repeating | C ++ implementation to count the number of pairs whose difference is atmost K in an array ; Function to count the number of pairs whose difference is atmost K in an array ; Sorting the Array ; Variable to store the count of pairs whose difference is atmost K ; Loop to consider the consecutive pairs of the array ; if Pair found increment the index by 2 ; Driver Code ; Function Call
#include <iostream> NEW_LINE #include <bits/stdc++.h> NEW_LINE using namespace std ; int countPairs ( int arr [ ] , int k , int n ) { sort ( arr , arr + n ) ; int pair = 0 ; int index = 0 ; while ( index < n - 1 ) { if ( arr [ index + 1 ] - arr [ index ] <= k ) { pair += 1 ; index += 2 ; } else { index += 1 ; } } return pair ; } int main ( ) { int arr [ ] = { 1 , 4 , 3 , 7 , 5 } ; int k = 2 ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int count = countPairs ( arr , k , n ) ; cout << count << endl ; ; }