Minimum Absolute Difference in an Array

  • + 0 comments

    Java:

    public static int minimumAbsoluteDifference(List<Integer> arr) {
        if (arr == null || arr.size() < 2) {
          throw new IllegalArgumentException(
              "Array must contain at least two elements.");
        }
        Collections.sort(arr);
        //System.out.println(arr);
        int n = arr.size();
        int minAbsDiff = Integer.MAX_VALUE;
    
        for (int i = 0; i < n - 1; i++) {
          int abs = arr.get(i + 1) - arr.get(i);
          minAbsDiff = Math.min(minAbsDiff, abs);
        }
    
        return minAbsDiff;
      }