Minimum pairs required to be removed such that the array does not contain any pair with sum K | Java program for the above approach ; Function to find the maximum count of pairs required to be removed such that no pairs exist whose sum equal to K ; Stores maximum count of pairs required to be removed such that no pairs exist whose sum equal to K ; Base Case ; Sort the array ; Stores index of left pointer ; Stores index of right pointer ; Stores sum of left and right pointer ; If s equal to k ; Update cntPairs ; Update left ; Update right ; If s > k ; Update right ; Update left ; Return the cntPairs ; Driver Code ; Function call
import java . util . * ; class GFG { static int maxcntPairsSumKRemoved ( int [ ] arr , int k ) { int cntPairs = 0 ; if ( arr . length <= 1 ) return cntPairs ; Arrays . sort ( arr ) ; int left = 0 ; int right = arr . length - 1 ; while ( left < right ) { int s = arr [ left ] + arr [ right ] ; if ( s == k ) { cntPairs += 1 ; left += 1 ; right -= 1 ; } else if ( s > k ) right -= 1 ; else left += 1 ; } return cntPairs ; } public static void main ( String [ ] args ) { int [ ] arr = { 1 , 2 , 3 , 4 } ; int K = 5 ; System . out . println ( maxcntPairsSumKRemoved ( arr , K ) ) ; } }