Count of distinct index pair ( i , j ) such that element sum of First Array is greater | 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 ; Number of elements in a and b ; Array a ; Array b
function numberOfPairs ( a , b , n ) { let c = new Array ( n ) ; for ( let i = 0 ; i < n ; i ++ ) { c [ i ] = a [ i ] - b [ i ] ; } c . sort ( function ( a , b ) { return a - b } ) ; let answer = 0 ; for ( let i = 1 ; i < n ; i ++ ) { if ( c [ i ] <= 0 ) continue ; let pos = - 1 ; for ( let j = 0 ; j < n ; j ++ ) { if ( c [ i ] + c [ j ] > 0 ) { pos = j ; break ; } } answer += ( i - pos ) ; } return answer ; } let n = 5 ; let a = [ 1 , 2 , 3 , 4 , 5 ] ; let b = [ 2 , 5 , 6 , 1 , 9 ] ; document . write ( numberOfPairs ( a , b , n ) ) ;