Leetcode 1619. Mean of Array After Removing Some Elements
You are given an integer array arr
. Using a sliding window, find the mean of the array after dropping the smallest 5% and the largest 5% of the elements.
Constraints:
20 <= arr.length <= 1000
arr.length
is a multiple of 20.-10^5 <= arr[i] <= 10^5
import java.util.Arrays;
public class MeanAfterRemoval {
public static double trimMean(int[] arr) {
Arrays.sort(arr);
int n = arr.length;
int removeCount = n / 20;
int sum = 0;
for (int i = removeCount; i < n - removeCount; i++) {
sum += arr[i];
}
double mean = (double) sum / (n - 2 * removeCount);
return mean;
}
public static void main(String[] args) {
int[] arr = {6,2,7,5,1,2,0,9,8,12,2,3,4,5,2,7,8,3,11,6,
4,6,9,5,4,5,6,5,8,10,2,3,5,6,8,9,10,11,12,14};
System.out.println("Trimmed Mean: " + trimMean(arr));
}
}
This approach ensures that we account for removing extreme values to find a reliable mean of the trimmed array.
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?