Jishan's Log 17: Minimum Absolute Difference in an Array
Hackerrank Greedy
So this problem is your basic problem.
The Problem:
We are given an array and we are to find the minimum absolute difference.
The Solution:
- We will sort the array
- Create a storage variable to keep track of minimum difference
- We will take the initial abs difference between the first two pairs
- if it's 0, we return it
- else we iterate through the loop taking two pairs
- if we find their difference is 0, return it
- else compare if it is smaller than what we had stored
- Finally, we return that storage variable
The Code:
#include <bits/stdc++.h>
using namespace std;
int min(int a, int b) {
return a < b ? a : b;
}
int minimumAbsoluteDifference(vector<int> arr) {
sort(arr.begin(), arr.end());
int res = abs(arr[1] - arr[0]);
if(res == 0) {
return 0;
}
for(int i = 0; i < arr.size()-1; ++i) {
int absDiff = abs(arr[i+1] - arr[i]);
if (absDiff == 0) {
return 0;
}
else if(res > absDiff) {
res = absDiff;
}
}
return res;
}
int main()
{
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int n;
cin >> n;
vector<int> arr;
for(int i = 0; i < n; ++i) {
int x;
cin >> x;
arr.push_back(x);
}
cout << minimumAbsoluteDifference(arr) << "\n";
return 0;
}
Comments
Post a Comment