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.
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.
publicstaticintminimumAbsoluteDifference(List<Integer>arr){// Write your code hereintminAbsDiff=Integer.MAX_VALUE;Collections.sort(arr);for(inti=0;i<(arr.size()-1);i++){intcurDiffVal=Math.abs(arr.get(i)-arr.get(i+1));minAbsDiff=Math.min(minAbsDiff,curDiffVal);}returnminAbsDiff;}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Minimum Absolute Difference in an Array
You are viewing a single comment's thread. Return to all 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.