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.
1import java.util.Arrays;
2
3public class AverageSalary {
4 public static double average(int[] salary) {
5 Arrays.sort(salary);
6 int sum = 0;
7 for (int i = 1; i < salary.length - 1; i++) {
8 sum += salary[i];
9 }
10 return sum / (double) (salary.length - 2);
11 }
12}
The Java solution sorts the salary array. It then calculates the sum of the elements from index 1 to the second-to-last index, thus excluding the minimum and maximum. The average is computed by dividing this sum by the number of the elements considered.
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.
1#include <vector>
2#include <algorithm>
3using namespace std;
4
5double average(vector<int>& salary) {
int minSalary = INT_MAX, maxSalary = INT_MIN;
int total = 0;
for(int s : salary) {
minSalary = min(minSalary, s);
maxSalary = max(maxSalary, s);
total += s;
}
return (total - minSalary - maxSalary) / ((double)salary.size() - 2);
}
C++ uses a loop to compute the total sum of salaries while simultaneously finding the minimum and maximum values. This avoids sorting and hence can be more efficient. After obtaining these values, the minimum and maximum are subtracted from the total sum to compute the average of the remaining elements.