text: Count maximum possible pairs from an array having sum K | C # program for the above approach ; Function to find the maximum number of pairs with a sum K such that same element can 't be used twice ; Initialize a hashmap ; Store the readonly result ; Iterate over the array nums [ ] ; Decrement its frequency in map and increment the result by 1 ; Increment its frequency by 1 if it is already present in map . Otherwise , set its frequency to 1 ; Print the result ; Driver Code ; Function Call
code: using System ; using System . Collections . Generic ; class GFG { public static void maxPairs ( int [ ] nums , int k ) { Dictionary < int , int > map = new Dictionary < int , int > ( ) ; int result = 0 ; foreach ( int i in nums ) { if ( map . ContainsKey ( i ) && map [ i ] > 0 ) { map [ i ] = map [ i ] - 1 ; result ++ ; } else { if ( ! map . ContainsKey ( k - i ) ) map . Add ( k - i , 1 ) ; else map [ i ] = map [ i ] + 1 ; } } Console . WriteLine ( result ) ; } public static void Main ( String [ ] args ) { int [ ] arr = { 1 , 2 , 3 , 4 } ; int K = 5 ; maxPairs ( arr , K ) ; } }