Two elements whose sum is closest to zero | Python3 implementation using STL ; Modified to sort by abolute values ; Absolute value shows how close it is to zero ; If found an even close value update min and store the index ; Driver code
import sys NEW_LINE def findMinSum ( arr , n ) : NEW_LINE INDENT for i in range ( 1 , n ) : NEW_LINE INDENT if ( not abs ( arr [ i - 1 ] ) < abs ( arr [ i ] ) ) : NEW_LINE INDENT arr [ i - 1 ] , arr [ i ] = arr [ i ] , arr [ i - 1 ] NEW_LINE DEDENT DEDENT Min = sys . maxsize NEW_LINE x = 0 NEW_LINE y = 0 NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if ( abs ( arr [ i - 1 ] + arr [ i ] ) <= Min ) : NEW_LINE INDENT Min = abs ( arr [ i - 1 ] + arr [ i ] ) NEW_LINE x = i - 1 NEW_LINE y = i NEW_LINE DEDENT DEDENT print ( " The ▁ two ▁ elements ▁ whose ▁ sum ▁ is ▁ minimum ▁ are " , arr [ x ] , " and " , arr [ y ] ) NEW_LINE DEDENT arr = [ 1 , 60 , - 10 , 70 , - 80 , 85 ] NEW_LINE n = len ( arr ) NEW_LINE findMinSum ( arr , n ) NEW_LINE