How to find the two elements in a list whose sum is closest to zero in VB.NET

1 Answer

0 votes
Imports System
Imports System.Collections.Generic

Module ClosestToZero
    ' Function to find the two elements whose sum is closest to zero
    Sub FindClosestToZero(lst As List(Of Integer))
        If lst.Count < 2 Then
            Console.WriteLine("list must have at least two elements.")
            Return
        End If

        ' Step 1: Sort the list
        Dim sortedlst As New List(Of Integer)(lst)
        sortedlst.Sort()

        Dim left As Integer = 0
        Dim right As Integer = sortedlst.Count - 1
        Dim closestSum As Integer = Integer.MaxValue
        Dim closestPair(1) As Integer

        ' Step 2: Use two-indexes technique
        While left < right
            Dim sum As Integer = sortedlst(left) + sortedlst(right)

            ' Update closest sum and pair if needed
            If Math.Abs(sum) < Math.Abs(closestSum) Then
                closestSum = sum
                closestPair(0) = sortedlst(left)
                closestPair(1) = sortedlst(right)
            End If

            ' Move indexess
            If sum < 0 Then
                left += 1 ' Increase sum by moving left indexes
            Else
                right -= 1 ' Decrease sum by moving right indexes
            End If
        End While

        ' Output the result
        Console.WriteLine("The two elements whose sum is closest to zero are: " &
                          closestPair(0) & " and " & closestPair(1) &
                          " with a sum of " & closestSum & ".")
    End Sub

    Sub Main()
        Dim lst As New List(Of Integer) From {23, -26, -88, -42, 55, 99, -11, 90, -13, 17, -31}
		
        FindClosestToZero(lst)
    End Sub

End Module


' run:
'
' The two elements whose sum is closest to zero are: -88 and 90 with a sum of 2.
' 


 



answered Sep 13 by avibootz
edited Sep 13 by avibootz
...