Sponsored
Sponsored
One straightforward way to solve this problem is to sort the array and then ignore the first and last elements (which will be the minimum and maximum once sorted). After this, calculate the average of the remaining elements.
This approach leverages the fact that sorting will automatically place the minimum value at the beginning and the maximum value at the end of the array, allowing us to easily exclude them by slicing the array.
Time Complexity: O(n log n) due to the sorting step.
Space Complexity: O(n) in the worst case due to the sorting algorithm.
1function averageExcludingMinMax(salary) {
2 salary.sort((a, b) => a - b);
3 const sum = salary.slice(1, -1).reduce((acc, val) => acc + val, 0);
4 return sum / (salary.length - 2);
5}
This JavaScript solution sorts the array and then uses the slice method to exclude the minimum and maximum values. The reduce method is used to calculate the sum of the sliced array, which is then divided by the length of the sliced array to get the average.
Instead of sorting, we can solve the problem using a single pass through the array. We find the minimum and maximum while calculating the total sum of elements. After determining the sum, minimum, and maximum, the average can be easily calculated by excluding the minimum and maximum from the sum.
Time Complexity: O(n), as it requires a single pass to determine the sum, minimum, and maximum.
Space Complexity: O(1), since no additional data structures are used apart from a few variables.
1using System;
2public class AverageSalary {
3 public static double Average(int[] salary) {
4 int minSalary = int.MaxValue, maxSalary = int.MinValue;
int total = 0;
foreach (int s in salary) {
minSalary = Math.Min(minSalary, s);
maxSalary = Math.Max(maxSalary, s);
total += s;
}
return (double)(total - minSalary - maxSalary) / (salary.Length - 2);
}
}
The C# solution iterates over the salary array once to find the sum, minimum, and maximum values. With these values calculated, the average is determined by removing the min and max from the total sum and dividing by the count of remaining elements.