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
using System ; using System . Collections . Generic ; class GfG { static int countPairs ( int [ ] A1 , int [ ] A2 , int n1 , int n2 , int K ) { int res = 0 ; Dictionary < int , int > m = new Dictionary < int , int > ( ) ; for ( int i = 0 ; i < n1 ; ++ i ) { int a ; if ( m . ContainsKey ( A1 [ i ] ) ) { a = m [ A1 [ i ] ] + 1 ; m . Remove ( A1 [ i ] ) ; m . Add ( A1 [ i ] , a ) ; } else m . Add ( A1 [ i ] , 1 ) ; } for ( int i = 0 ; i < n2 ; ++ i ) { int temp = K - A2 [ i ] ; if ( m . ContainsKey ( temp ) && m [ temp ] != 0 ) { res ++ ; m . Remove ( temp ) ; m . Add ( temp , m [ A1 [ i ] ] - 1 ) ; } } return res ; } public static void Main ( ) { int [ ] A1 = { 1 , 1 , 3 , 4 , 5 , 6 , 6 } ; int [ ] A2 = { 1 , 4 , 4 , 5 , 7 } ; int K = 10 ; int n1 = A1 . Length ; int n2 = A2 . Length ; Console . WriteLine ( countPairs ( A1 , A2 , n1 , n2 , K ) ) ; } }