Count pairs from two arrays having sum equal to K | C ++ implementation of above approach . ; Function to return the count of pairs having sum equal to K ; Initialize pairs to 0 ; create map of elements of array A1 ; count total pairs ; Every element can be part of at most one pair . ; return total pairs ; Driver program ; function call to print required answer
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countPairs ( int A1 [ ] , int A2 [ ] , int n1 , int n2 , int K ) { int res = 0 ; unordered_map < int , int > m ; for ( int i = 0 ; i < n1 ; ++ i ) m [ A1 [ i ] ] ++ ; for ( int i = 0 ; i < n2 ; ++ i ) { int temp = K - A2 [ i ] ; if ( m [ temp ] != 0 ) { res ++ ; m [ temp ] -- ; } } return res ; } int main ( ) { int A1 [ ] = { 1 , 1 , 3 , 4 , 5 , 6 , 6 } ; int A2 [ ] = { 1 , 4 , 4 , 5 , 7 } , K = 10 ; int n1 = sizeof ( A1 ) / sizeof ( A1 [ 0 ] ) ; int n2 = sizeof ( A2 ) / sizeof ( A2 [ 0 ] ) ; cout << countPairs ( A1 , A2 , n1 , n2 , K ) ; return 0 ; }