Member-only story
Leetcode 1491: Average Salary Excluding the Minimum and Maximum Salary
1 min readJun 28, 2020
In this Leetcode problem, we try to compute the average of an array excluding max the max and min value.
Solution
A couple of ideas for the solution:
- Go through the array and keep track of the
sum
of all elements but the currentmin
andmax
- At each step we can update
min
ormax
if needed and add the previousmin
ormax
(as they are not the min or max anymore) - Otherwise, just add the value to
sum
- At the end compute the average with
average = sum / (n — 2)
- The time complexity is
O(n)
class Solution {
public double average(int[] salary) {
int min = Math.min(salary[0], salary[1]);
int max = Math.max(salary[0], salary[1]);
int sum = 0;
int n = salary.length;
for (int i = 2; i < n; i++) {
int v = salary[i];
if (v < min) {
sum += min;
min = v;
} else if (v > max) {
sum += max;
max = v;
} else {
sum += v;
}
}
return ((double) sum) / ((double) n - 2);
}
}
Happy coding :)