Numbers of pairs from an array whose average is also present in the array | CPP program for the above approach ; Function to count the total count of pairs having sum S ; Store the total count of all elements in map mp ; Initialize value to 0 , if key not found ; Stores the total count of total pairs ; Iterate through each element and increment the count ; If the value ( S - arr [ i ] ) exists in the map hm ; Update the twice count ; Return the half of twice_count ; Function to count of pairs having whose average exists in the array ; Stores the total count of pairs ; Use set to remove duplicates ; Insert all the element in the set S ; For every sum find the getCountPairs ; Return the total count of pairs ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int getCountPairs ( int arr [ ] , int N , int S ) { map < int , int > mp ; for ( int i = 0 ; i < N ; i ++ ) { mp [ arr [ i ] ] ++ ; } int twice_count = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( mp . find ( S - arr [ i ] ) != mp . end ( ) ) { twice_count += mp [ S - arr [ i ] ] ; } if ( S - arr [ i ] == arr [ i ] ) twice_count -- ; } return twice_count / 2 ; } int countPairs ( int arr [ ] , int N ) { int count = 0 ; set < int > S ; for ( int i = 0 ; i < N ; i ++ ) S . insert ( arr [ i ] ) ; for ( int ele : S ) { int sum = 2 * ele ; count += getCountPairs ( arr , N , sum ) ; } return count ; } int main ( ) { int N = 6 ; int arr [ ] = { 4 , 2 , 5 , 1 , 3 , 5 } ; cout << ( countPairs ( arr , N ) ) ; }