Count pairs ( i , j ) from an array such that | arr [ i ] | and | arr [ j ] | both lies between | arr [ i ] | C ++ program for the above approach ; Function to find pairs ( i , j ) such that | arr [ i ] | and | arr [ j ] | lies in between | arr [ i ] - arr [ j ] | and | arr [ i ] + arr [ j ] | ; Calculate absolute value of all array elements ; Sort the array ; Stores the count of pairs ; Traverse the array ; Increment left ; Add to the current count of pairs ; Print the answer ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findPairs ( int arr [ ] , int N ) { for ( int i = 0 ; i < N ; i ++ ) arr [ i ] = abs ( arr [ i ] ) ; sort ( arr , arr + N ) ; int left = 0 ; int ans = 0 ; for ( int right = 0 ; right < N ; right ++ ) { while ( 2 * arr [ left ] < arr [ right ] ) left ++ ; ans += ( right - left ) ; } cout << ans ; } int main ( ) { int arr [ ] = { 1 , 3 , 5 , 7 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; findPairs ( arr , N ) ; return 0 ; }