Count maximum possible pairs from an array having sum K | Java program for the above approach ; Function to count the maximum number of pairs from given array with sum K ; Sort array in increasing order ; Stores the final result ; Initialize the left and right pointers ; Traverse array until start < end ; Decrement right by 1 ; Increment left by 1 ; Increment result and left pointer by 1 and decrement right pointer by 1 ; Print the result ; Driver Code ; Function Call
import java . io . * ; import java . util . * ; class GFG { public static void maxPairs ( int [ ] nums , int k ) { Arrays . sort ( nums ) ; int result = 0 ; int start = 0 , end = nums . length - 1 ; while ( start < end ) { if ( nums [ start ] + nums [ end ] > k ) end -- ; else if ( nums [ start ] + nums [ end ] < k ) start ++ ; else { start ++ ; end -- ; result ++ ; } } System . out . println ( result ) ; } public static void main ( String [ ] args ) { int [ ] arr = { 1 , 2 , 3 , 4 } ; int K = 5 ; maxPairs ( arr , K ) ; } }