Similar Problems

Similar Problems not available

Mean Of Array After Removing Some Elements - Leetcode Solution

Companies:

LeetCode:  Mean Of Array After Removing Some Elements Leetcode Solution

Difficulty: Easy

Topics: sorting array  

Problem Statement:

Given an integer array arr, return the mean of the remaining integers after removing the smallest 5% and the largest 5% of the elements.

Example Input and Output:

Input: arr = [10, 20, 30, 40, 50] Output: 30.00000

Input: arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] Output: 5.50000

Solution:

  1. Sort the input array in ascending order.
  2. Calculate the number of elements that should be removed from the start and end of the array.
  3. Calculate the sum of the remaining elements in the array.
  4. Calculate the mean of the remaining elements in the array.

Code:

class Solution { public double trimMean(int[] arr) { Arrays.sort(arr); int n = arr.length; int s = (int) (n * 0.05); double sum = 0.0; for (int i = s; i < n - s; i++) { sum += arr[i]; } return sum / (n - 2 * s); } }

Complexity Analysis:

Time Complexity: O(n log n) Sorting the array takes O(n log n) time.

Space Complexity: O(1) The space required is constant.

Mean Of Array After Removing Some Elements Solution Code

1