Average Salary Excluding the Minimum and Maximum Salary

Language Options

C++ Solution |
Python Solution

Code Solution


class Solution {
  public double average(int[] salary) {
    final double sum = Arrays.stream(salary).sum();
    final int mx = Arrays.stream(salary).max().getAsInt();
    final int mn = Arrays.stream(salary).min().getAsInt();
    return (sum - mx - mn) / (salary.length - 2);
  }
}

Problem Description

So, you want to find the average salary of a group of people, but wait! You can’t just take the average like a normal person. No, no, no! You have to exclude the highest and lowest salaries. Why? Because apparently, we need to make sure that the rich and the poor don’t skew our average. It’s like trying to find the average height of a group of friends but excluding the basketball player and the toddler. Makes perfect sense, right?

Imagine you’re at a party, and everyone is bragging about their salaries. You have one friend who makes a million bucks, and another who barely scrapes by. You want to find out what the average salary is among your friends, but you don’t want those two to mess up your calculations. So, you decide to kick them out of the party (figuratively, of course) and calculate the average of the rest. Voilà! You’ve got your answer!

Approach

The approach taken in the code is straightforward:

  1. Calculate the total sum of all salaries.
  2. Identify the maximum and minimum salaries.
  3. Subtract the maximum and minimum from the total sum.
  4. Divide the result by the number of salaries minus two (to account for the excluded salaries).

Time and Space Complexity

Time Complexity

O(n), where n is the number of salaries. This is because we traverse the salary array multiple times to calculate the sum, maximum, and minimum.

Space Complexity

O(1), as we are using a constant amount of space for variables.

Real-World Example

Let’s say you’re in a company where the salaries are as varied as the coffee preferences in the break room. You have:

  • Alice: $100,000
  • Bob: $50,000
  • Charlie: $200,000
  • Dave: $30,000
  • Eve: $70,000

If you want to find the average salary excluding Alice and Charlie (the highest and lowest earners), you would sum up Bob, Dave, and Eve’s salaries, which gives you $50,000 + $30,000 + $70,000 = $150,000. Then, divide that by 3 (the number of remaining salaries), and you get an average of $50,000.

Similar Problems

If you enjoyed this problem, you might also like: