We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.

# Minimum Absolute Difference in an Array

# Minimum Absolute Difference in an Array

+ 43 comments 1)sort 2)consider diff between the first pair as min 3)compare all "consecutive pair min" with the one in step2 to get the least min.

+ 2 comments Why this is under greedy algo ? What is the greedy property in this problem?

+ 3 comments Arrays.sort(arr); int minimumDifference = Integer.MAX_VALUE; for (int i = 0; i < arr.length - 1; i++) { int difference = arr[i + 1] - arr[i]; if (difference < minimumDifference) { minimumDifference = difference; if (minimumDifference == 0) { return 0; } } } return minimumDifference;

+ 3 comments Is it possible to solve it better than O (n log n)?

+ 1 comment JavaScript version that I like and feel is readable and clean.

function minimumAbsoluteDifference(arr) { // Sort arr.sort(); let minDiff; // Loop through the consecutive pairs, if 0 return, else set min diff for (let i = 0; i < arr.length; i++) { let absDiff = Math.abs(arr[i+1] - arr[i]); if (!minDiff || absDiff < minDiff) minDiff = absDiff; if (minDiff === 0) return 0; } return minDiff; }

Load more conversations

Sort 588 Discussions, By:

Please Login in order to post a comment