Count maximum possible pairs from an array having sum K | 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
def maxPairs ( nums , k ) : NEW_LINE INDENT nums = sorted ( nums ) NEW_LINE result = 0 NEW_LINE start , end = 0 , len ( nums ) - 1 NEW_LINE while ( start < end ) : NEW_LINE INDENT if ( nums [ start ] + nums [ end ] > k ) : NEW_LINE INDENT end -= 1 NEW_LINE DEDENT elif ( nums [ start ] + nums [ end ] < k ) : NEW_LINE INDENT start += 1 NEW_LINE DEDENT else : NEW_LINE INDENT start += 1 NEW_LINE end -= 1 NEW_LINE result += 1 NEW_LINE DEDENT DEDENT print ( result ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 2 , 3 , 4 ] NEW_LINE K = 5 NEW_LINE maxPairs ( arr , K ) NEW_LINE DEDENT