Average Salary Excluding the Minimum and Maximum Salary
Problem
Given salary[] of unique integers, return the average salary after excluding the min and max salaries.
salary = [4000,3000,1000,2000]2500.0def average(salary):
total = mn = mx = 0
mn, mx = float('inf'), float('-inf')
for s in salary:
total += s; mn = min(mn, s); mx = max(mx, s)
return (total - mn - mx) / (len(salary) - 2)
function average(salary) {
let sum = 0, mn = Infinity, mx = -Infinity;
for (const s of salary) { sum += s; if (s < mn) mn = s; if (s > mx) mx = s; }
return (sum - mn - mx) / (salary.length - 2);
}
class Solution {
public double average(int[] salary) {
long sum = 0; int mn = Integer.MAX_VALUE, mx = Integer.MIN_VALUE;
for (int s : salary) { sum += s; mn = Math.min(mn, s); mx = Math.max(mx, s); }
return (double)(sum - mn - mx) / (salary.length - 2);
}
}
double average(vector& salary) {
long long sum = 0; int mn = INT_MAX, mx = INT_MIN;
for (int s : salary) { sum += s; mn = min(mn, s); mx = max(mx, s); }
return (double)(sum - mn - mx) / (salary.size() - 2);
}
Explanation
We do not actually need to remove anything from the list. Since exactly one minimum and one maximum are excluded, we can add everything up and then just subtract the min and the max at the end.
In a single pass we keep three running values: a total of all salaries, the smallest seen mn, and the largest seen mx. Each salary updates all three with simple comparisons.
The average of the remaining people is then (total - mn - mx) divided by (len(salary) - 2) — we subtract 2 from the count because two people (the min and max earners) were dropped.
Example: salary = [4000, 3000, 1000, 2000]. The total is 10000, with mn = 1000 and mx = 4000. So (10000 - 1000 - 4000) / (4 - 2) = 5000 / 2 = 2500.0.