Count pairs from two arrays with difference exceeding K | set 2 | C ++ program for the above approach ; Function to count pairs that satisfy the given conditions ; Stores the count of pairs ; If v1 [ ] is smaller than v2 [ ] ; Sort the array v1 [ ] ; Traverse the array v2 [ ] ; Returns the address of the first number which is >= v2 [ j ] - k ; Increase the count by all numbers less than v2 [ j ] - k ; Otherwise ; Sort the array v2 [ ] ; Traverse the array v1 [ ] ; Returns the address of the first number which is > v1 [ i ] + k ; Increase the count by all numbers greater than v1 [ i ] + k ; Return the total count of pairs ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countPairs ( int v1 [ ] , int v2 [ ] , int n , int m , int k ) { int count = 0 ; if ( n <= m ) { sort ( v1 , v1 + n ) ; for ( int j = 0 ; j < m ; j ++ ) { int index = lower_bound ( v1 , v1 + n , v2 [ j ] - k ) - v1 ; count += index ; } } else { sort ( v2 , v2 + m ) ; for ( int i = 0 ; i < n ; i ++ ) { int index = upper_bound ( v2 , v2 + m , v1 [ i ] + k ) - v2 ; count += m - index ; } } return count ; } int main ( ) { int arr [ ] = { 5 , 9 , 1 , 8 } ; int brr [ ] = { 10 , 12 , 7 , 4 , 2 , 3 } ; int K = 3 ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int M = sizeof ( brr ) / sizeof ( brr [ 0 ] ) ; cout << countPairs ( arr , brr , N , M , K ) ; return 0 ; }