-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathMin. Absolute Difference In Array-Coding Ninjas CP Course
67 lines (64 loc) · 1.55 KB
/
Min. Absolute Difference In Array-Coding Ninjas CP Course
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
Min. Absolute Difference In Array
Send Feedback
Given an integer array A of size N, find and return the minimum absolute difference between any two elements in the array.
We define the absolute difference between two elements ai and aj (where i != j ) as |ai - aj|.
Input format :
The first line of input contains an integer that denotes the number of test cases. Let us denote it by the symbol T.
Each of the test cases contain two lines. The first line of each test case contains an integer, that denotes the value of N. The following line contains N space separated integers, that denote the array elements.
Constraints :
1 <= T <= 10
2 <= N <= 10^5
0 <= arr[i] <= 10^8
Output Format :
You have to print minimum difference for each test case in new line.
Sample Input 1:
1
5
2 9 0 4 5
Sample Output 1:
1
#include<iostream>
#include<algorithm>
#include<climits>
using namespace std;
int mod(int a)
{
if(a<0)
{
return -a;
}
return a;
}
int minAbsoluteDiff(int arr[], int n) {
/* Don't write main().
* Don't read input, it is passed as function argument.
* Return output and don't print it.
* Taking input and printing output is handled automatically.
*/
sort(arr, arr+n);
int i=0;
int j=1;
int minimum=INT_MAX;
while(j<n)
{
if(mod(arr[i]-arr[j])<minimum)
{
minimum=mod(arr[i]-arr[j]);
}
i++;
j++;
}
return minimum;
}
int main(){
int t;cin>>t;
while(t--){
int n;cin>>n;
int arr[n];
for(int i=0;i<n;i++){
cin>>arr[i];
}
cout<<minAbsoluteDiff(arr,n)<<endl;
}
return 0;
}