Find a triplet in an array whose sum is closest to a given number | Python3 implementation of the above approach ; Function to return the sum of a triplet which is closest to x ; To store the closest sum ; Run three nested loops each loop for each element of triplet ; Update the closestSum ; Return the closest sum found ; Driver code
import sys NEW_LINE def solution ( arr , x ) : NEW_LINE INDENT closestSum = sys . maxsize NEW_LINE for i in range ( len ( arr ) ) : NEW_LINE INDENT for j in range ( i + 1 , len ( arr ) ) : NEW_LINE INDENT for k in range ( j + 1 , len ( arr ) ) : NEW_LINE INDENT if ( abs ( x - closestSum ) > abs ( x - ( arr [ i ] + arr [ j ] + arr [ k ] ) ) ) : NEW_LINE INDENT closestSum = ( arr [ i ] + arr [ j ] + arr [ k ] ) NEW_LINE DEDENT 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