Average Salary Excluding the Minimum and Maximum Salary
Leetcode Daily Challenge (1st May, 2023)
Problem Statement:-
You are given an array of unique integers salary
where salary[i]
is the salary of the i<sup>th</sup>
employee.
Return the average salary of employees excluding the minimum and maximum salary. Answers within 10<sup>-5</sup>
of the actual answer will be accepted.
Link: https://leetcode.com/problems/average-salary-excluding-the-minimum-and-maximum-salary/description/
Problem Explanation with examples:-
Example 1
Input: salary = [4000,3000,1000,2000]
Output: 2500.00000
Explanation: Minimum salary and maximum salary are 1000 and 4000 respectively.
Average salary excluding minimum and maximum salary is (2000+3000) / 2 = 2500
Example 2
Input: salary = [1000,2000,3000]
Output: 2000.00000
Explanation: Minimum salary and maximum salary are 1000 and 3000 respectively.
Average salary excluding minimum and maximum salary is (2000) / 1 = 2000
Constraints
3 <= salary.length <= 100
1000 <= salary[i] <= 10<sup>6</sup>
All the integers of
salary
are unique.
Intuition:-
- Easiest way is to sort the array and then take the average of the elements from index 1 to n-2.
Solution:-
Sort the array.
Take the sum of the elements from index 1 to n-2 and divide it by n-2.
Return the result.
Code:-
JAVA Solution
class Solution {
public double average(int[] salary) {
Arrays.sort(salary);
double sum = 0;
for (int i = 1; i < salary.length-1; i++) {
sum += salary[i];
}
return sum / (salary.length - 2);
}
}
Python Solution
class Solution:
def average(self, salary: List[int]) -> float:
return sum(sorted(salary)[1:len(salary)-1])/(len(salary)-2)
Complexity Analysis:-
TIME:-
The time complexity is O(nlogn) where n is the length of the array. Sorting takes O(nlogn) time.
SPACE:-
The space complexity is O(1) since we do not use any extra space.