Minimum Absolute Difference in an Array
Problem Link: Minimum Absolute Difference in an Array
Consider an array of integers, A=a0,a1,……..an-1. We define the absolute difference between two elements, ai and aj ,where(i != j) to be the absolute value ai — aj.
Given an array of n integers, find and print the minimum absolute difference between any two elements in the array.
Input Format
The first line contains a single integer n denoting (the number of integers).
The second line contains n space-separated integers describing the respective values of a0,a1,……..an-1.
Constraints
- 2 <= n <= 105
- -109 <= ai <= 109
Output Format
Print the minimum absolute difference between any two elements in the array.
Sample Input 0
3
3 -7 0
Sample Output 0
3
Explanation 0
With n=3 integers in our array, we have three possible pairs: (3,-7), (3,0) , and (-7,0). The absolute values of the differences between these pairs are as follows:
- | 3- -7 | = 10
- | 3- 0 | = 3
- | -7–0 | = 7
Notice that if we were to switch the order of the numbers in these pairs, the resulting absolute values would still be the same. The smallest of these possible absolute differences is 3, so we print 3 as our answer.
SOLUTION
This is also an easy problem. Take a vector and sort it and find the minimum difference of adjacent element(as vector is sorted).
CODE
#include<iostream>
#include<algorithm>
#include<cmath>
#include<vector>
#include<string>
using namespace std;
#define ll long long
int main()
{
int n; cin>>n;
vector<ll> v;
for(int i=0;i<n;i++)
{
ll x; cin>>x; v.push_back(x);
}
sort(v.begin(),v.end());
ll min = abs(v[1] - v[0]);
for(int i=2;i<n;i++)
{
if(abs(v[i]-v[i-1]) < min)
min = abs(v[i]-v[i-1]);
}
cout<<min<<endl;
}