text: Count distinct pairs with given sum | C # program to implement the above approach ; Function to count distinct pairs in array whose sum equal to K ; Stores count of distinct pairs whose sum equal to K ; Store frequency of each distinct element of the array ; Update frequency of arr [ i ] ; Traverse the map ; Stores key value of the map ; If i is the half of K ; If frequency of i greater than 1 ; Update cntPairs ; Update cntPairs ; Driver Code
code: using System ; using System . Collections . Generic ; class GFG { static int cntDisPairs ( int [ ] arr , int N , int K ) { int cntPairs = 0 ; Dictionary < int , int > cntFre = new Dictionary < int , int > ( ) ; for ( int i = 0 ; i < N ; i ++ ) { if ( cntFre . ContainsKey ( arr [ i ] ) ) cntFre [ arr [ i ] ] = cntFre [ arr [ i ] ] + 1 ; else cntFre . Add ( arr [ i ] , 1 ) ; } foreach ( KeyValuePair < int , int > it in cntFre ) { int i = it . Key ; if ( 2 * i == K ) { if ( cntFre [ i ] > 1 ) cntPairs += 2 ; } else { if ( cntFre . ContainsKey ( K - i ) ) { cntPairs += 1 ; } } } cntPairs = cntPairs / 2 ; return cntPairs ; } public static void Main ( String [ ] args ) { int [ ] arr = { 5 , 6 , 5 , 7 , 7 , 8 } ; int N = arr . Length ; int K = 13 ; Console . Write ( cntDisPairs ( arr , N , K ) ) ; } }