Member-only story

Leetcode 1491: Average Salary Excluding the Minimum and Maximum Salary

Pierre-Marie Poitevin
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.

Problem statement

Solution

A couple of ideas for the solution:

  • Go through the array and keep track of the sum of all elements but the current min and max
  • At each step we can update min or max if needed and add the previous min or max (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 :)

--

--

Pierre-Marie Poitevin
Pierre-Marie Poitevin

No responses yet