Minimum pairs required to be removed such that the array does not contain any pair with sum K | C ++ 14 program to implement 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maxcntPairsSumKRemoved ( vector < int > arr , int k ) { int cntPairs = 0 ; if ( arr . size ( ) <= 1 ) return cntPairs ; sort ( arr . begin ( ) , arr . end ( ) ) ; int left = 0 ; int right = arr . size ( ) - 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 ; } int main ( ) { vector < int > arr = { 1 , 2 , 3 , 4 } ; int K = 5 ; cout << ( maxcntPairsSumKRemoved ( arr , K ) ) ; return 0 ; }