Average Salary Excluding the Minimum and Maximum Salary Problem
Description
LeetCode Problem 1491.
You are 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. 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] <= 10^6- All the integers of
salaryare unique.
Solution
Approach: One Pass for Sum, Minimum and Maximum
The salaries are all unique, so exactly one value is the minimum and exactly one is the maximum. Removing them leaves n - 2 salaries whose sum is the total sum minus those two values.
So in one pass we compute the sum, the minimum and the maximum, and return (sum - min - max) / (n - 2). Do the division in floating point: with integer division, [1000,2000,2001,4000] would give 2000 instead of 2000.5.
The sum fits in a 32-bit integer: at most 100 * 10^6 = 10^8.
Complexity: O(n) time and O(1) extra space.
class Solution:
def average(self, salary: List[int]) -> float:
# Salaries are unique, so exactly one minimum and one maximum are left out.
return (sum(salary) - min(salary) - max(salary)) / (len(salary) - 2)