Count of distinct index pair ( i , j ) such that element sum of First Array is greater | Java program of the above approach ; Function to find the number of pairs . ; Array c [ ] where c [ i ] = a [ i ] - b [ i ] ; Sort the array c ; Initialise answer as 0 ; Iterate from index 0 to n - 1 ; If c [ i ] <= 0 then in the sorted array c [ i ] + c [ pos ] can never greater than 0 where pos < i ; Which is equivalent to c [ j ] >= - c [ i ] + 1 ; Add ( i - pos ) to answer ; Return the answer ; Driver code ; Number of elements in a and b ; array a ; array b
import java . util . * ; class GFG { static int numberOfPairs ( int [ ] a , int [ ] b , int n ) { int c [ ] = new int [ n ] ; for ( int i = 0 ; i < n ; i ++ ) { c [ i ] = a [ i ] - b [ i ] ; } Arrays . sort ( c ) ; int answer = 0 ; for ( int i = 1 ; i < n ; i ++ ) { if ( c [ i ] <= 0 ) continue ; int pos = - 1 ; for ( int j = 0 ; j < n ; j ++ ) { if ( c [ i ] + c [ j ] > 0 ) { pos = j ; break ; } } answer += ( i - pos ) ; } return answer ; } public static void main ( String [ ] args ) { int n = 5 ; int a [ ] = { 1 , 2 , 3 , 4 , 5 } ; int b [ ] = { 2 , 5 , 6 , 1 , 9 } ; System . out . println ( numberOfPairs ( a , b , n ) ) ; } }