This is somewhat “not-easy-as-it-seems” array question. because there are a lot of things which we would not consider at first. Only After a thorough testing we can get the ultimate solution.
Return the "centered" average of an array of ints, which we'll say is the mean average of the values, except not counting the largest and smallest values in the array. Use int division to produce the final average. You may assume that the array is length 3 or more.
centeredAverage({1, 2, 3, 4, 100}) → 3
centeredAverage({1, 1, 5, 5, 10, 8, 7}) → 5
centeredAverage({-10, -4, -2, -4, -2, 0}) → –3
Solution
public int centeredAverage(int[] nums) {if(nums.length <3 ) return 0;int len=nums.length;int max=Integer.MIN_VALUE ;int min=Integer.MAX_VALUE ;int sum=0 ;int mini=0; // subscript of max ,minint maxi=0;// get max,min values and their subscriptsfor(int i=0;i<len;i++){if(nums[i]>max){max=nums[i];maxi=i;}if(nums[i]<min){min=nums[i];mini=i;}}// end for// compute the averagefor(int j=0 ; j<len; j++){if(maxi==mini) {// all the elements are samesum=nums[0];break;}if(j != maxi && j != mini)sum+=nums[j];}// end forreturn sum/(len-2);}