The Leetcode problem "Average Salary Excluding the Minimum and Maximum Salary" asks you to calculate the average salary from a list of salaries, but excluding the minimum and maximum salary values.
Given an array called salary
, where each element is a positive integer representing an employee's salary, you should:
salary
contains at least 3 elements.To solve this problem, let's first consider the most direct approach:
Let's break down the efficient solution step by step:
total sum
, minimum
, and maximum
salary values. You can initialize min and max to the first element of the array.sum
.min
if the current salary is lower than the current min.max
if the current salary is higher than the current max.min
and max
from the sum
to get the sum of the remaining salaries.len(salary) - 2
. Divide the adjusted sum by this number to get the average.This approach is optimal because it only requires a single pass through the array (O(n) time), and uses constant extra space.
Let's work through an example to see how the solution unfolds:
Input: salary = [4000, 3000, 1000, 2000]
2500.0
class Solution:
def average(self, salary: List[int]) -> float:
total = sum(salary)
min_salary = min(salary)
max_salary = max(salary)
return (total - min_salary - max_salary) / (len(salary) - 2)
class Solution {
public:
double average(vector<int>& salary) {
int total = 0, min_salary = salary[0], max_salary = salary[0];
for (int s : salary) {
total += s;
if (s < min_salary) min_salary = s;
if (s > max_salary) max_salary = s;
}
return (total - min_salary - max_salary) / double(salary.size() - 2);
}
};
class Solution {
public double average(int[] salary) {
int total = 0, min_salary = salary[0], max_salary = salary[0];
for (int s : salary) {
total += s;
if (s < min_salary) min_salary = s;
if (s > max_salary) max_salary = s;
}
return (total - min_salary - max_salary) / (double)(salary.length - 2);
}
}
var average = function(salary) {
let total = 0, min_salary = salary[0], max_salary = salary[0];
for (let s of salary) {
total += s;
if (s < min_salary) min_salary = s;
if (s > max_salary) max_salary = s;
}
return (total - min_salary - max_salary) / (salary.length - 2);
};
Brute-force Approach:
The key insight for this problem is that you don't need to sort or create extra arrays to exclude the minimum and maximum salaries. By tracking the total sum, minimum, and maximum in a single pass, you can efficiently compute the required average in O(n) time and O(1) space. This approach is both simple and optimal, making it a great example of how a little analysis can lead to elegant code.