Given an array of integers, find the minimum absolute difference between any two elements in the array.
Example:
Input: n=5, arr[]={1,-3,71,68,17}
Output: 3
Approach
Java
import java.util.Arrays;public class MinAbsDiffInArray {public static void main(String[] args) {int[] arr = { 1, -3, 71, 68, 17 };int result = minimumAbsoluteDifference(arr);System.out.println(result);}private static int minimumAbsoluteDifference(int[] arr) {Arrays.sort(arr);int ans = Integer.MAX_VALUE;for (int i = 1; i < arr.length; i++)ans = Math.min(ans, arr[i] - arr[i - 1]);return ans;}}
C++
#include <bits/stdc++.h>using namespace std;int minimumAbsoluteDifference(vector<int> arr){sort(arr.begin(), arr.end());int ans = INT_MAX;for (int i = 1; i < arr.size(); i++)ans = min(ans, arr[i] - arr[i - 1]);return ans;}int main(){int n = 5;vector<int> arr = {1, -3, 71, 68, 17};int result = minimumAbsoluteDifference(arr);cout << result << "\n";return 0;}
No comments:
Post a Comment