Average Salary Excluding the Minimum and Maximum Salary in C++

Problem Description

Welcome to the world of salary calculations, where we pretend to care about fairness while secretly wishing for that sweet, sweet paycheck! The problem at hand is to calculate the average salary of a group of employees, but with a twist: we need to exclude the highest and lowest salaries. Why? Because who wants to be reminded of that one guy who always makes more than everyone else or that intern who’s still living off ramen noodles?

Imagine you’re at a party, and everyone is bragging about their salaries. You don’t want to hear about the millionaire CEO or the intern who’s still figuring out how to use a microwave. Instead, you want the average of the “normal” salaries. That’s what this problem is all about!

Code Solution


class Solution {
 public:
  double average(vector& salary) {
    const double sum = accumulate(salary.begin(), salary.end(), 0.0);
    const int mx = ranges::max(salary);
    const int mn = ranges::min(salary);
    return (sum - mx - mn) / (salary.size() - 2);
  }
};

Approach

The approach here is as straightforward as it gets. First, we calculate the total sum of all salaries. Then, we find the maximum and minimum salaries using the max and min functions. Finally, we subtract these two from the total sum and divide by the number of salaries minus two (because we excluded the highest and lowest). Voilà! You have your average salary of the “normal” folks.

Time and Space Complexity

Complexity Type Complexity
Time Complexity O(n), where n is the number of salaries.
Space Complexity O(1), as we are using a constant amount of space for our variables.

Real-World Example

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

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

If you calculate the average excluding Alice and Dave, you’d be left with Bob, Charlie, and Eve. The average salary of these three is a much more relatable figure, and it’s a great way to keep the conversation going without making anyone feel awkward!

Similar Problems

If you enjoyed this problem, you might also like these:

  • 2-Sum Solution in C++