Count pairs with given sum | C # implementation of simple method to find count of pairs with given sum ; Returns number of pairs in arr [ 0. . n - 1 ] with sum equal to ' sum ' ; Store counts of all elements in map hm ; initializing value to 0 , if key not found ; iterate through each element and increment the count ( Notice that every pair is counted twice ) ; if ( arr [ i ] , arr [ i ] ) pair satisfies the condition , then we need to ensure that the count is decreased by one such that the ( arr [ i ] , arr [ i ] ) pair is not considered ; return the half of twice_count ; Driver Code
using System ; using System . Collections . Generic ; class GFG { public static int [ ] arr = new int [ ] { 1 , 5 , 7 , - 1 , 5 } ; public static int getPairsCount ( int n , int sum ) { Dictionary < int , int > hm = new Dictionary < int , int > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( ! hm . ContainsKey ( arr [ i ] ) ) { hm [ arr [ i ] ] = 0 ; } hm [ arr [ i ] ] = hm [ arr [ i ] ] + 1 ; } int twice_count = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( hm [ sum - arr [ i ] ] != 0 ) { twice_count += hm [ sum - arr [ i ] ] ; } if ( sum - arr [ i ] == arr [ i ] ) { twice_count -- ; } } return twice_count / 2 ; } public static void Main ( string [ ] args ) { int sum = 6 ; Console . WriteLine ( " Count ▁ of ▁ pairs ▁ is ▁ " + getPairsCount ( arr . Length , sum ) ) ; } }