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.
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 <= 1001000 <= salary[i] <= 106salary are unique.One straightforward way to solve this problem is to sort the array and then ignore the first and last elements (which will be the minimum and maximum once sorted). After this, calculate the average of the remaining elements.
This approach leverages the fact that sorting will automatically place the minimum value at the beginning and the maximum value at the end of the array, allowing us to easily exclude them by slicing the array.
The implementation sorts the salary list. Then, it calculates the sum of the array, excluding the first and last elements which are the minimum and maximum values after sorting. The average is then computed by dividing this sum by the number of remaining elements, which is the total length minus 2.
JavaScript
Java
Time Complexity: O(n log n) due to the sorting step.
Space Complexity: O(n) in the worst case due to the sorting algorithm.
Instead of sorting, we can solve the problem using a single pass through the array. We find the minimum and maximum while calculating the total sum of elements. After determining the sum, minimum, and maximum, the average can be easily calculated by excluding the minimum and maximum from the sum.
C++ uses a loop to compute the total sum of salaries while simultaneously finding the minimum and maximum values. This avoids sorting and hence can be more efficient. After obtaining these values, the minimum and maximum are subtracted from the total sum to compute the average of the remaining elements.
C#
Time Complexity: O(n), as it requires a single pass to determine the sum, minimum, and maximum.
Space Complexity: O(1), since no additional data structures are used apart from a few variables.
| Approach | Complexity |
|---|---|
| Sorting and Slicing | Time Complexity: O(n log n) due to the sorting step. |
| Single Traversal | Time Complexity: O(n), as it requires a single pass to determine the sum, minimum, and maximum. |
Average Salary Excluding the Minimum and Maximum Salary || LeetCode 1491 • BarikZone • 2,930 views views
Watch 9 more video solutions →Practice Average Salary Excluding the Minimum and Maximum Salary with our built-in code editor and test cases.
Practice on FleetCodePractice this problem
Open in Editor