Find a triplet in an array whose sum is closest to a given number | Python3 implementation of the approach ; Function to return the sum of a triplet which is closest to x ; Sort the array ; To store the closest sum ; Fix the smallest number among the three integers ; Two pointers initially pointing at the last and the element next to the fixed element ; While there could be more pairs to check ; Calculate the sum of the current triplet ; If the sum is more closer than the current closest sum ; If sum is greater then x then decrement the second pointer to get a smaller sum ; Else increment the first pointer to get a larger sum ; Return the closest sum found ; Driver code
import sys NEW_LINE def solution ( arr , x ) : NEW_LINE INDENT arr . sort ( ) ; NEW_LINE closestSum = sys . maxsize ; NEW_LINE for i in range ( len ( arr ) - 2 ) : NEW_LINE INDENT ptr1 = i + 1 ; ptr2 = len ( arr ) - 1 ; NEW_LINE while ( ptr1 < ptr2 ) : NEW_LINE INDENT sum = arr [ i ] + arr [ ptr1 ] + arr [ ptr2 ] ; NEW_LINE if ( abs ( x - sum ) < abs ( x - closestSum ) ) : NEW_LINE INDENT closestSum = sum ; NEW_LINE DEDENT if ( sum > x ) : NEW_LINE INDENT ptr2 -= 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT ptr1 += 1 ; NEW_LINE DEDENT DEDENT DEDENT return closestSum ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ - 1 , 2 , 1 , - 4 ] ; NEW_LINE x = 1 ; NEW_LINE print ( solution ( arr , x ) ) ; NEW_LINE DEDENT