package main
import (
"fmt"
"math"
"sort"
)
// Function to find the two elements whose sum is closest to zero
func findClosestToZero(arr []int) {
if len(arr) < 2 {
fmt.Println("arr must have at least two elements.")
return
}
// Step 1: Sort the arr
sortedArr := make([]int, len(arr))
copy(sortedArr, arr)
sort.Ints(sortedArr)
left := 0
right := len(sortedArr) - 1
closestSum := math.MaxInt64
closestPair := [2]int{0, 0}
// Step 2: Use two-indexed technique
for left < right {
sum := sortedArr[left] + sortedArr[right]
// Update closest sum and pair if needed
if abs(sum) < abs(closestSum) {
closestSum = sum
closestPair[0] = sortedArr[left]
closestPair[1] = sortedArr[right]
}
// Move indexeds
if sum < 0 {
left++ // Increase sum by moving left indexed
} else {
right-- // Decrease sum by moving right indexed
}
}
// Output the result
fmt.Printf("The two elements whose sum is closest to zero are: %d and %d with a sum of %d.\n",
closestPair[0], closestPair[1], closestSum)
}
// Helper function for absolute value
func abs(x int) int {
if x < 0 {
return -x
}
return x
}
func main() {
arr := []int{23, -26, -88, -42, 55, 99, -11, 90, -13, 17, -31}
findClosestToZero(arr)
}
/*
run:
The two elements whose sum is closest to zero are: -88 and 90 with a sum of 2.
*/