Count pairs from two arrays with difference exceeding K | C ++ program to implement the above approach ; Function to count pairs that satisfy the given conditions ; Stores index of the left pointer . ; Stores index of the right pointer ; Stores count of total pairs that satisfy the conditions ; Sort arr [ ] array ; Sort brr [ ] array ; Traverse both the array and count then pairs ; If the value of ( brr [ j ] - arr [ i ] ) exceeds K ; Update cntPairs ; Update ; Update j ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int count_pairs ( int arr [ ] , int brr [ ] , int N , int M , int K ) { int i = 0 ; int j = 0 ; int cntPairs = 0 ; sort ( arr , arr + N ) ; sort ( brr , brr + M ) ; while ( i < N && j < M ) { if ( brr [ j ] - arr [ i ] > K ) { cntPairs += ( M - j ) ; i ++ ; } else { j ++ ; } } return cntPairs ; } 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 << count_pairs ( arr , brr , N , M , K ) ; return 0 ; }