CodingBat Java Array-2 centeredAverage
I found the answer on the internet, which is:
public int centeredAverage(int[] nums) {
int largest = 0, smallest = 0, result = 0;
for(int i = 0; i < nums.length; i++) {
if(nums[i] >= nums[largest] && i != smallest) {
largest = i;
} else if(nums[i] <= nums[smallest] && i != largest) {
smallest = i;
}
}
for(int i = 0; i < nums.length; i++) {
if(i != largest && i != smallest) {
result += nums[i];
}
}
return (int)(result / (nums.length - 2)); }But I'm having a hard time understanding what's going on here. First, I don't get why i is being used in the first for-loop to declare largest and smallest. Isn't it supposed to be "nums" for the first loop? Also, why does i need to be compared to smallest and largest to see if they're not equal to [I]i?


Sign In
Create Account


Back to top









