Examples:
Input:
test1[] = {-3, 10, 8, -2, 2, -1}
Output:
-2 and 2
Here,
The sum of -2 and 2 is 0.
#include <bits/stdc++.h>
#include <stdlib.h>
#include <math.h>
using namespace std;
void closestToZero(int arr[], int n)
{
// Initialize variables
int sum = 0, sum_min = INT_MAX, l = 0, r = n - 1, l_min = 0, r_min = n - 1;
if (n < 2)
{
cout << "Invalid Input";
return;
}
// sort the elements
sort(arr, arr + n);
while (l < r)
{
sum = arr[l] + arr[r];
// finding minimum sum
if (abs(sum) < abs(sum_min))
{
sum_min = sum;
l_min = l;
r_min = r;
}
if (sum < 0)
l++;
else
r--;
}
cout << "Sum closest to zero elements: "
<< arr[l_min] << " and " << arr[r_min];
}
int main()
{
int arr[100], N;
cout << "Enter Number of elements: ";
cin >> N;
for (int i = 0; i < N; i++)
{
cin >> arr[i];
}
closestToZero(arr, N);
return 0;
}
Output:
Enter Number of elements: 8
-4 2 6 5 -7 -1 9 -8
Sum closest to zero elements: -8 and 9
Here, (2,-1) and (5,-4) also answer
0 Comments