Pairs with Difference less than K | C ++ code to find count of Pairs with difference less than K . ; to sort the array . ; Keep incrementing result while subsequent elements are within limits . ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countPairs ( int a [ ] , int n , int k ) { sort ( a , a + n ) ; int res = 0 ; for ( int i = 0 ; i < n ; i ++ ) { int j = i + 1 ; while ( j < n && a [ j ] - a [ i ] < k ) { res ++ ; j ++ ; } } return res ; } int main ( ) { int a [ ] = { 1 , 10 , 4 , 2 } ; int k = 3 ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; cout << countPairs ( a , n , k ) << endl ; return 0 ; }