#include <iostream>
#include <vector>
#include <algorithm> // sort
#include <climits> // INT_MAX
void findClosestToZero(const std::vector<int>& vec) {
if (vec.size() < 2) {
std::cout << "vec must have at least two elements." << std::endl;
return;
}
// Step 1: Sort the vec
std::vector<int> sortedvec = vec;
std::sort(sortedvec.begin(), sortedvec.end());
int left = 0, right = sortedvec.size() - 1;
int closestSum = INT_MAX;
int closestPair[2] = {0, 0};
// Step 2: Use two-indexed technique
while (left < right) {
int sum = sortedvec[left] + sortedvec[right];
// Update closest sum and pair if needed
if (std::abs(sum) < std::abs(closestSum)) {
closestSum = sum;
closestPair[0] = sortedvec[left];
closestPair[1] = sortedvec[right];
}
// Move indexeds
if (sum < 0) {
++left; // Increase sum by moving left indexed
} else {
--right; // Decrease sum by moving right indexed
}
}
// Output the result
std::cout << "The two elements whose sum is closest to zero are: "
<< closestPair[0] << " and " << closestPair[1]
<< " with a sum of " << closestSum << "." << std::endl;
}
int main() {
std::vector<int> vec = {23, -26, -88, -42, 55, 99, -11, 90, -13, 17, -31};
findClosestToZero(vec);
}
/*
run:
The two elements whose sum is closest to zero are: -88 and 90 with a sum of 2.
*/