Problem:
Return the "centered" average of an array of ints, which we'll say is the mean average of the values, except ignoring the largest and smallest values in the array. If there are multiple copies of the smallest value, ignore just one copy, and likewise for the largest value. 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) { Arrays.sort(nums); int count = 0; int sum = 0; for (int i = 1; i < nums.length - 1; i++){ sum += nums[i]; count++;} return sum / count; }
M not getting it...
ReplyDeleteThe question is saying that if u have more than one copies of max or min nums then just escape only one copy and include others to find avg.
how to do that ?
with out built in function
Deletepublic int centeredAverage(int[] nums) {
int max,min,sum;
max=min=nums[0];
sum=0;
for(int i=0;inums[i])?nums[i]:min);
max=((max<nums[i])?nums[i]:max);
}
return (sum-max-min)/(nums.length-2);
}
ohhhh got it... u r sorting the array.;)
ReplyDeleteThe soultion wrong
ReplyDeletepublic int centeredAverage(int[] nums) {
ReplyDeleteint sum = 0;
int largest = nums[0];
int smallest = nums[0];
for (int i = 0; i < nums.length; i++) {
smallest = Math.min(smallest, nums[i]);
largest = Math.max(largest, nums[i]);
sum = sum + nums[i];
}
sum = sum - largest;
sum = sum - smallest;
return sum / (nums.length - 2);
}
public int centeredAverage(int[] nums) {
ReplyDeleteint temp = 0;
int min = nums[0];
int max = nums[0];
for(int i = 0; imax){
max = nums[i];
}
temp = temp+nums[i];
}
int tempo = temp-max-min;
int size = nums.length-2;
int avg = tempo/size;
return avg;
}
public int centeredAverage(int[] nums) {
ReplyDeleteArrays.sort(nums);
return (nums.length%2 == 0) ? (nums[nums.length/2 - 1] + nums[nums.length/2])/2 : nums[nums.length/2];
}