Count pairs from two arrays with difference exceeding K | Java 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
import java . util . * ; class GFG { static int count_pairs ( int arr [ ] , int brr [ ] , int N , int M , int K ) { int i = 0 ; int j = 0 ; int cntPairs = 0 ; Arrays . sort ( arr ) ; Arrays . sort ( brr ) ; while ( i < N && j < M ) { if ( brr [ j ] - arr [ i ] > K ) { cntPairs += ( M - j ) ; i ++ ; } else { j ++ ; } } return cntPairs ; } public static void main ( String args [ ] ) { int arr [ ] = { 5 , 9 , 1 , 8 } ; int brr [ ] = { 10 , 12 , 7 , 4 , 2 , 3 } ; int K = 3 ; int N = arr . length ; int M = brr . length ; System . out . println ( count_pairs ( arr , brr , N , M , K ) ) ; } }