Leetcode 1491. Average Salary Excluding the Minimum and Maximum Salary
Given an array of unique integers salary
where salary[i]
is the salary of the i-th
employee, return the average salary of employees excluding the minimum and maximum salary.
Example:
Input: salary = [4000, 3000, 1000, 2000]
Output: 2500.00000
Explanation: Minimum salary: 1000, maximum salary: 4000
Average salary: (2000+3000)/2 = 2500
#include <iostream>
#include <vector>
#include <numeric> // for accumulate
#include <algorithm> // for min_element and max_element
double averageSalaryExcludingMinMax(const std::vector<int>& salary) {
int minSalary = *std::min_element(salary.begin(), salary.end());
int maxSalary = *std::max_element(salary.begin(), salary.end());
int totalSum = std::accumulate(salary.begin(), salary.end(), 0);
// Calculate the adjusted sum by excluding the minimum and maximum salaries
int adjustedSum = totalSum - minSalary - maxSalary;
// Calculate the average excluding the smallest and largest salaries
int n = salary.size() - 2;
return static_cast<double>(adjustedSum) / n;
}
int main() {
std::vector<int> salary = {4000, 3000, 1000, 2000};
double result = averageSalaryExcludingMinMax(salary);
std::cout << "Average Salary Excluding Min and Max: " << result << std::endl;
return 0;
}
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?