Leetcode 1491. Average Salary Excluding the Minimum and Maximum Salary
You are given an array of unique integers salary
where salary[i]
is the salary of the ith
employee.
Return the average salary of employees excluding the minimum and maximum salary. Answers within 10^-5 of the actual answer will be accepted.
Q: What is the range of values for salary
elements?
A: Each element in salary
is a positive integer.
Q: How many elements are there in the salary
array?
A: There are at least three elements in the salary
array.
Q: What should be done if all elements in salary
are the same?
A: This scenario is not possible since all salaries need to be unique as per the problem statement.
To solve this problem:
public class Solution {
public double average(int[] salary) {
// Initial variables to track the minimum and maximum salary
int minSalary = Integer.MAX_VALUE;
int maxSalary = Integer.MIN_VALUE;
// Sum of all salaries
int sumSalaries = 0;
// Calculate the total sum and find min and max salaries
for (int sal : salary) {
if (sal < minSalary) {
minSalary = sal;
}
if (sal > maxSalary) {
maxSalary = sal;
}
sumSalaries += sal;
}
// Subtract min and max salary from the sum
sumSalaries -= (minSalary + maxSalary);
// Return the average excluding min and max salary
return sumSalaries / (double)(salary.length - 2);
}
}
The time complexity of this solution is O(n), where n is the number of elements in the salary
array. This is because we iterate over the array a single time to find the sum, minimum, and maximum salaries.
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?