HackerRank(greedy): Minimum Absolute Difference in an Array
Problem:
Consider an array of integers, . We define the absolute difference between two elements, and (where ), to be the absolute value of .
Given an array of integers, find and print the minimum absolute difference between any two elements in the array.
Consider an array of integers, . We define the absolute difference between two elements, and (where ), to be the absolute value of .
Given an array of integers, find and print the minimum absolute difference between any two elements in the array.
Input Format
The first line contains a single integer denoting (the number of integers).
The second line contains space-separated integers describing the respective values of .
The second line contains space-separated integers describing the respective values of .
Constraints
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 integers in our array, we have three possible pairs: , , and . The absolute values of the differences between these pairs are as follows:
Solutions:
Note: Simple O(n^2) solution won't work because of time constraints. So, use this below O(N logN) solution which uses sorting the array first, then uses O(N) to compare adjacent differences.
Solutions:
Note: Simple O(n^2) solution won't work because of time constraints. So, use this below O(N logN) solution which uses sorting the array first, then uses O(N) to compare adjacent differences.
#include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> #include <climits> using namespace std; int main() { int n; long long min = INT_MAX; cin>>n; vector<long long>arr(n); for(int i=0; i<n; i++) cin>>arr[i]; sort(arr.begin(), arr.end()); for(int i=0;i<n-1;i++) if(min>abs(arr[i]-arr[i+1])) min=abs(arr[i]-arr[i+1]); cout<<min; return 0; }
Comments
Post a Comment