Number of indices pair such that element pair sum from first Array is greater than second Array | Function to get the number of pairs of indices { i , j } in the given two arrays A and B such that A [ i ] + A [ j ] > B [ i ] + B [ j ] ; Intitializing the difference array D ; Computing the difference between the elements at every index and storing it in the array D ; Sort the array D ; Variable to store the total number of pairs that satisfy the given condition ; Loop to iterate through the difference array D and find the total number of pairs of indices that follow the given condition ; If the value at the index i is positive , then it remains positive for any pairs with j such that j > i . ; If the value at that index is negative then we need to find the index of the value just greater than - D [ i ] ; Driver code
function getPairs ( A , B , n ) { let D = new Array ( n ) ; for ( let i = 0 ; i < n ; i ++ ) { D [ i ] = A [ i ] - B [ i ] ; } D . sort ( ( a , b ) => a - b ) ; let total = 0 ; for ( let i = n - 1 ; i >= 0 ; i -- ) { if ( D [ i ] > 0 ) { total += n - i - 1 ; } else { let k = upper_bound ( D , 0 , D . length , - D [ i ] ) total += n - k ; } } return total ; } function upper_bound ( a , low , high , element ) { while ( low < high ) { let middle = low + Math . floor ( ( high - low ) / 2 ) ; if ( a [ middle ] > element ) high = middle ; else low = middle + 1 ; } return low ; } let n = 5 ; let A = new Array ( ) ; let B = new Array ( ) ; A . push ( 4 ) ; A . push ( 8 ) ; A . push ( 2 ) ; A . push ( 6 ) ; A . push ( 2 ) ; B . push ( 4 ) ; B . push ( 5 ) ; B . push ( 4 ) ; B . push ( 1 ) ; B . push ( 3 ) ; document . write ( getPairs ( A , B , n ) )