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.
This is my java 8 solutions, feel free to ask me any questions.
My very fist solution using bruteforce:
publicstaticintminimumAbsoluteDifference(List<Integer>arr){intminimum=Integer.MAX_VALUE;intn=arr.size();//Iterate through all combinations taken 2 of given array,//Calculate thier abs different and look for the minimum.for(inti=0;i<n;i++){for(intj=i+1;j<n;j++){intfirst=arr.get(i);intsecond=arr.get(j);intdiff=Math.abs(first-second);//Update minumum absolute differrenceif(minimum>diff){minimum=diff;}}}returnminimum;}
Second look (refer):
publicstaticintminimumAbsoluteDifference(List<Integer>arr){intminimum=Integer.MAX_VALUE;intn=arr.size();//Perform sort the given list ascendingarr.sort(null);//Iterate through the sorted list to calculate difffor(inti=1;i<n;i++){intprevious=arr.get(i-1);intcurrent=arr.get(i);intdiff=Math.abs(previous-current);if(diff<minimum){minimum=diff;}}returnminimum;}
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 →
This is my java 8 solutions, feel free to ask me any questions.
My very fist solution using bruteforce:
Second look (refer):