Average Salary Excluding the Minimum and Maximum Salary
EasyUpdated: Aug 2, 2025
Practice on:
Problem
You are given an array of unique integers salary where salary[i] is the salary of the ith employee.
Return the average salary of employees excluding the minimum and maximum salary. Answers within 10-5 of the actual answer will be accepted.
Examples
Example 1
Input: salary = [4000,3000,1000,2000]
Output: 2500.00000
Explanation: Minimum salary and maximum salary are 1000 and 4000 respectively.
Average salary excluding minimum and maximum salary is (2000+3000) / 2 = 2500
Example 2
Input: salary = [1000,2000,3000]
Output: 2000.00000
Explanation: Minimum salary and maximum salary are 1000 and 3000 respectively.
Average salary excluding minimum and maximum salary is (2000) / 1 = 2000
Constraints
3 <= salary.length <= 1001000 <= salary[i] <= 10^6- All the integers of
salaryare unique.
Solution
Method 1 – Sorting and Summing
Intuition
The minimum and maximum salaries can be excluded by sorting or by finding them directly. By summing all salaries and subtracting the minimum and maximum, we get the total of the remaining salaries. Dividing by the count of remaining employees gives the required average.
Approach
- Find the minimum and maximum values in the salary array.
- Calculate the sum of all salaries.
- Subtract the minimum and maximum from the sum.
- Divide the result by (n - 2), where n is the number of employees.
- Return the computed average.
Code
C++
class Solution {
public:
double average(vector<int>& salary) {
int mn = salary[0], mx = salary[0], sum = 0;
for (int s : salary) {
mn = min(mn, s);
mx = max(mx, s);
sum += s;
}
return (sum - mn - mx) * 1.0 / (salary.size() - 2);
}
};
Go
type Solution struct{}
func (Solution) Average(salary []int) float64 {
mn, mx, sum := salary[0], salary[0], 0
for _, s := range salary {
if s < mn {
mn = s
}
if s > mx {
mx = s
}
sum += s
}
return float64(sum-mn-mx) / float64(len(salary)-2)
}
Java
class Solution {
public double average(int[] salary) {
int mn = salary[0], mx = salary[0], sum = 0;
for (int s : salary) {
mn = Math.min(mn, s);
mx = Math.max(mx, s);
sum += s;
}
return (sum - mn - mx) * 1.0 / (salary.length - 2);
}
}
Kotlin
class Solution {
fun average(salary: IntArray): Double {
var mn = salary[0]
var mx = salary[0]
var sum = 0
for (s in salary) {
mn = minOf(mn, s)
mx = maxOf(mx, s)
sum += s
}
return (sum - mn - mx).toDouble() / (salary.size - 2)
}
}
Python
class Solution:
def average(self, salary: list[int]) -> float:
mn: int = min(salary)
mx: int = max(salary)
total: int = sum(salary)
return (total - mn - mx) / (len(salary) - 2)
Rust
impl Solution {
pub fn average(salary: Vec<i32>) -> f64 {
let mn = *salary.iter().min().unwrap();
let mx = *salary.iter().max().unwrap();
let sum: i32 = salary.iter().sum();
(sum - mn - mx) as f64 / (salary.len() as f64 - 2.0)
}
}
Complexity
- ⏰ Time complexity:
O(N)(single pass to find min, max, and sum) - 🧺 Space complexity:
O(1)(constant extra space)