Count maximum possible pairs from an array having sum K | 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
def maxPairs ( nums , k ) : NEW_LINE INDENT m = { } NEW_LINE result = 0 NEW_LINE for i in nums : NEW_LINE INDENT if ( ( i in m ) and m [ i ] > 0 ) : NEW_LINE INDENT m [ i ] = m [ i ] - 1 NEW_LINE result += 1 NEW_LINE DEDENT else : NEW_LINE INDENT if k - i in m : NEW_LINE INDENT m [ k - i ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT m [ k - i ] = 1 NEW_LINE DEDENT DEDENT DEDENT print ( result ) NEW_LINE DEDENT arr = [ 1 , 2 , 3 , 4 ] NEW_LINE K = 5 NEW_LINE maxPairs ( arr , K ) NEW_LINE