import java.util.Arrays; // for sorting
import java.util.List; // for input list
import java.util.ArrayList;
public class ClosestToZero {
// Function to find the two elements whose sum is closest to zero
public static void findClosestToZero(List<Integer> lst) {
if (lst.size() < 2) {
System.out.println("list must have at least two elements.");
return;
}
// Step 1: Sort the list
List<Integer> sortedlst = new ArrayList<>(lst);
sortedlst.sort(Integer::compareTo);
int left = 0;
int right = sortedlst.size() - 1;
int closestSum = Integer.MAX_VALUE;
int[] closestPair = new int[2];
// Step 2: Use two-indexed technique
while (left < right) {
int sum = sortedlst.get(left) + sortedlst.get(right);
// Update closest sum and pair if needed
if (Math.abs(sum) < Math.abs(closestSum)) {
closestSum = sum;
closestPair[0] = sortedlst.get(left);
closestPair[1] = sortedlst.get(right);
}
// Move indexeds
if (sum < 0) {
left++; // Increase sum by moving left indexed
} else {
right--; // Decrease sum by moving right indexed
}
}
// Output the result
System.out.println("The two elements whose sum is closest to zero are: "
+ closestPair[0] + " and " + closestPair[1]
+ " with a sum of " + closestSum + ".");
}
public static void main(String[] args) {
List<Integer> lst = Arrays.asList(23, -26, -88, -42, 55, 99, -11, 90, -13, 17, -31);
findClosestToZero(lst);
}
}
/*
run:
The two elements whose sum is closest to zero are: -88 and 90 with a sum of 2.
*/