This is a level 2 Array question.:
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
Easy as it seems , thought it takes some tests to figure out the ultimate solution. which cannot be broken.For the passing array can have zero’s , can contain only one digit , etc, this here is my approach. pretty straight forward.
1: public int centeredAverage(int[] nums) {2:3: if(nums.length <3 ) return 0;4:5: int len=nums.length;6: int max=Integer.MIN_VALUE ; // stores the max value, initialized with the smallest possible int value7: int min=Integer.MAX_VALUE ; // stores the min value, initialized with the largest possible int value8: int sum=0 ;9: int mini=0; // indexes of the max/min values10: int maxi=0;11:12: for(int i=0;i<len;i++){13: if(nums[i]>max){14: max=nums[i];15: maxi=i;16: }17: if(nums[i]<min){18: min=nums[i];19: mini=i;20: }21: }22:23: for(int j=0 ; j<len; j++){24: if(maxi==mini) {// all the elements are same25: sum=nums[0];26: break;27: }28: if(j != maxi && j != mini)29: sum+=nums[j];30: }31: return sum/(len-2); //32:33: }
…