forked from amankayat/HackerRank-Solution-Algorithm-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclosest_number.cpp
More file actions
44 lines (35 loc) · 725 Bytes
/
closest_number.cpp
File metadata and controls
44 lines (35 loc) · 725 Bytes
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
#include<iostream>
#include <bits/stdc++.h>
#include<cmath>
#include<vector>
#include<climits>
using namespace std;
int main(){
int n;
cin>>n;
vector<int> a;
for(int i=0;i<n;i++)
{
int x;
cin>>x;
a.push_back(x);
}
//sort using vector
//you can also use insertion sort or any sorting method here but one test case fails using any method so yu can use sort function to sorting
// this array
sort(a.begin(),a.end());
int store[n];
int min = INT_MAX;
//check which difference is min & find min
for(int i=0;i<n-1;i++){
store[i] = abs(a[i]-a[i+1]);
if(min>store[i])
min = store[i];
}
//checking
for(int i=0;i<n-1;i++){
if(abs(a[i]-a[i+1])==min){
cout<<a[i]<<" "<<a[i+1]<<" ";
}
}
}