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 hashm ; Store the final result ; Iterate over the array nums [ ] ; Decrement its frequency in m and increment the result by 1 ; Increment its frequency by 1 if it is already present in m . Otherwise , set its frequency to 1 ; Print the result ; Driver Code ; Function Call
code: #include <bits/stdc++.h> NEW_LINE #include <string.h> NEW_LINE using namespace std ; void maxPairs ( vector < int > nums , int k ) { map < int , int > m ; int result = 0 ; for ( auto i : nums ) { if ( m . find ( i ) != m . end ( ) && m [ i ] > 0 ) { m [ i ] = m [ i ] - 1 ; result ++ ; } else { m [ k - i ] = m [ k - i ] + 1 ; } } cout << result ; } int main ( ) { vector < int > arr = { 1 , 2 , 3 , 4 } ; int K = 5 ; maxPairs ( arr , K ) ; }