text: Count maximum possible pairs from an array having sum K | Java 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 final 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: import java . io . * ; import java . util . * ; class GFG { public static void maxPairs ( int [ ] nums , int k ) { Map < Integer , Integer > map = new HashMap < > ( ) ; int result = 0 ; for ( int i : nums ) { if ( map . containsKey ( i ) && map . get ( i ) > 0 ) { map . put ( i , map . get ( i ) - 1 ) ; result ++ ; } else { map . put ( k - i , map . getOrDefault ( k - i , 0 ) + 1 ) ; } } System . out . println ( result ) ; } public static void main ( String [ ] args ) { int [ ] arr = { 1 , 2 , 3 , 4 } ; int K = 5 ; maxPairs ( arr , K ) ; } }