Question: An Array of integers is given, both +ve and -ve. You need to find the two elements such that their sum is closest to zero.
For the below array, program should print -80 and 85.
# include <bits/stdc++.h>
# include <stdlib.h> /* for abs() */
# include <math.h>
using namespace std;
void minAbsSumPair(int arr[], int arr_size)
{
int inv_count = 0;
int l, r, min_sum, sum, min_l, min_r;
if(arr_size < 2)
{
cout << "Invalid Input";
return;
}
min_l = 0;
min_r = 1;
min_sum = arr[0] + arr[1];
for(l = 0; l < arr_size - 1; l++)
{
for(r = l + 1; r < arr_size; r++)
{
sum = arr[l] + arr[r];
if(abs(min_sum) > abs(sum))
{
min_sum = sum;
min_l = l;
min_r = r;
}
}
}
cout << "The two elements whose sum is minimum are "
<< arr[min_l] << " and " << arr[min_r];
}
int main()
{
int arr[] = {1, 60, -10, 70, -80, 85};
minAbsSumPair(arr, 6);
return 0;
}
The two elements whose sum is minimum are -80 and 85
Time complexity: O(n^2)
Algorithm
1) Sort all the elements of the input array using their absolute values.
2) Check absolute sum of arr[i-1] and arr[i] if their absolute sum is less than min update min with their absolute value.
3) Use two variables to store the index of the elements.
Implementation
#include <bits/stdc++.h>
using namespace std;
bool compare(int x, int y)
{
return abs(x) < abs(y);
}
void findMinSum(int arr[], int n)
{
sort(arr, arr + n, compare);
int min = INT_MAX, x, y;
for (int i = 1; i < n; i++) {
if (abs(arr[i - 1] + arr[i]) <= min) {
min = abs(arr[i - 1] + arr[i]);
x = i - 1;
y = i;
}
}
cout << "The two elements whose sum is minimum are "
<< arr[x] << " and " << arr[y];
}
int main()
{
int arr[] = { 1, 60, -10, 70, -80, 85 };
int n = sizeof(arr) / sizeof(arr[0]);
findMinSum(arr, n);
return 0;
}
|
Output:
The two elements whose sum is minimum are -80 and 85
Time Complexity: O(nlogn)
Space Complexity: O(1)
Comments
Post a Comment