Mean of Array After Removing Some Elements Problem
Description
LeetCode Problem 1619.
Given an integer array arr, return the mean of the remaining integers after removing the smallest 5% and the largest 5% of the elements.
Answers within 10^(-5) of the actual answer will be considered accepted.
Example 1:
Input: arr = [1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,3]
Output: 2.00000
Explanation: After erasing the minimum and the maximum values of this array, all elements are equal to 2, so the mean is 2.
Example 2:
Input: arr = [6,2,7,5,1,2,0,3,10,2,5,0,5,5,0,8,7,6,8,0]
Output: 4.00000
Example 3:
Input: arr = [6,0,7,0,7,5,7,8,3,4,0,7,8,1,6,8,1,1,2,4,8,1,9,5,4,3,8,5,10,8,6,6,1,0,6,10,8,2,3,4]
Output: 4.77778
Constraints:
20 <= arr.length <= 1000arr.lengthis a multiple of20.0 <= arr[i] <= 10^5
Solution
Approach: Sort and Average the Middle
After sorting, the smallest 5% of the elements are at the front and the largest 5% at the back. The length is a multiple of 20, so 5% of it is exactly n / 20 elements, with no rounding to worry about.
Skip n / 20 elements at each end and return the average of the rest, that is, their sum divided by n - 2 * (n / 20).
The sum is at most 1000 · 105 = 108, so it fits in a 32-bit integer, but dividing must be done in floating point (cast before dividing in Java, C++ and Go).
Complexity: O(n log n) time for the sort, and O(1) extra space besides it.
class Solution:
def trimMean(self, arr: List[int]) -> float:
arr.sort()
cut = len(arr) // 20 # 5% of the elements; the length is a multiple of 20
middle = arr[cut : len(arr) - cut]
return sum(middle) / len(middle)