Minimum Absolute Difference in an Array

  • + 0 comments

    My Java 8 solution, which passes all test cases, for Max 15 points:

    Code is fairly simple & self-explanatory. First sort the array. Then iterate through the array sequentially, calculate the Diff between adjacent sorted values, and compare that with the "minAbsDiff" value & update it (as needed). Because of the sort, we don't need nested loops.

        public static int minimumAbsoluteDifference(List<Integer> arr) {
            // Write your code here
            int minAbsDiff = Integer.MAX_VALUE;
    
            Collections.sort(arr);
    
            for (int i = 0 ; i < (arr.size() - 1) ; i++) {
                int curDiffVal = Math.abs(arr.get(i) - arr.get(i + 1));
                minAbsDiff = Math.min(minAbsDiff, curDiffVal);
            }
    
            return minAbsDiff;
        }