Minimum Absolute Difference in an Array

Sort by

recency

|

699 Discussions

|

  • + 0 comments

    Here is my c++ solution, you can find the explanation here : https://youtu.be/6SnD7A1TbJQ

    int minimumAbsoluteDifference(vector<int> arr) {
        sort(arr.begin(), arr.end());
        int result = INT_MAX;
        for(int i = 1; i < arr.size(); i++){
            int d = arr[i] - arr[i-1];
            if( d < result) result = d;
        }
        return result;
    }
    
  • + 0 comments

    Haskell

    module Main where
    
    import Data.List (sort)
    
    solve :: [Integer] -> Integer
    solve = minimum . map abs . (zipWith (-) <*> tail) . sort
    
    main :: IO ()
    main = getLine >> getLine >>= print . solve . map read . words
    
  • + 0 comments

    java:

        public static int minimumAbsoluteDifference(List<Integer> arr) {
        int minimumAbsoluteDifference = Integer.MAX_VALUE;
        arr.sort(Comparator.naturalOrder());
        for (int i = 0; i < arr.size() -1; i++) {
            int absoluteDifference = Math.abs(arr.get(i) - arr.get(i + 1));
            if(absoluteDifference < minimumAbsoluteDifference){
                minimumAbsoluteDifference = absoluteDifference;
            }
        }
        return minimumAbsoluteDifference;
        }
    
  • + 0 comments
    int minimumAbsoluteDifference(vector<int> arr) {
        
        // Sort the array first
        sort(arr.begin(), arr.end());
        
        // Initialize the minimum difference with a large value
        int ans = abs(arr[1] - arr[0]);
    
        // Compare consecutive elements for the minimum difference
        for (int i = 1; i < arr.size() - 1; i++) {
            ans = min(ans, abs(arr[i + 1] - arr[i]));
        }
    
        return ans;
    }
    
  • + 0 comments
    def minimumAbsoluteDifference(arr):
        minimum = 10e10
        Arr = sorted(arr)
        for i in range(1, len(Arr)):
            minimum = min(minimum, abs(Arr[i] - Arr[i-1]))
            if minimum == 0:
                return 0
        return minimum