The Wayback Machine - https://web.archive.org/web/20210131164010/https://www.geeksforgeeks.org/mean-of-given-array-after-removal-of-k-percent-of-smallest-and-largest-array-elements/
Skip to content
Related Articles

Related Articles

Mean of given array after removal of K percent of smallest and largest array elements
  • Last Updated : 31 Jan, 2021

Given an array arr[] and an integer K, the task is to remove K % percent array elements from the smallest and largest array elements and calculate the mean of the remaining array.

Examples:

Input: arr[] = {6, 2, 7, 5, 1, 2, 0, 3, 10, 2, 5, 0, 5, 5, 0, 8, 7, 6, 8, 0}, K = 5
Output: 4.00000
Explanation:
There are 20 elements in the array. Therefore, 5% of 20 is 1. ztherefore, 1 of the smallest elements (i.e. 0) is removed and 1 element of the largest elements (i.e. 0) is removed. Therefore, mean of the remaining array is 18.

Input: arr[] = {6, 0, 7, 0, 7, 5, 7, 8, 3, 4, 0, 7, 8, 1, 6, 8, 1, 1, 2, 4}, K = 10
Output: 4.31250



Approach:

  1. Sort the array arr[].
  2. Find the size of the array.
  3. Calculate the K-th percent of the size of the array.
  4. Now, add the elements present in the indices K% to (N – 1) – K%.
  5. Finally, find the mean of those elements.

Below is the implementation of the above approach:

C++14

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
  
// Function to calculate the mean
// of a given array after removal
// of Kth percent of smallest and
// largest array elements
void meanOfRemainingElements(int arr[],
                             int N, int K)
{
    // Sort the array
    sort(arr, arr + N);
  
    // Find the K-th percent
    // of the array size
    int kthPercent = (N * K) / 100;
    float sum = 0;
  
    // Traverse the array
    for (int i = 0; i < N; i++)
  
        // Skip the first K-th
        // percent & last K-th
        // percent array elements
        if (i >= kthPercent && i < (N - kthPercent))
            sum += arr[i];
  
    // Mean of the rest of elements
    float mean = sum
                 / (N - 2 * kthPercent);
  
    // Print mean upto 5 decimal places
    cout << fixed << setprecision(5) << mean << endl;
}
  
// Driver Code
int main()
{
  
    int arr[] = { 6, 2, 7, 5, 1, 2, 0, 3, 10, 2,
                  5, 0, 5, 5, 0, 8, 7, 6, 8, 0 };
    int arr_size = sizeof(arr) / sizeof(arr[0]);
    int K = 5;
  
    meanOfRemainingElements(arr, arr_size, K);
  
    return 0;
}

chevron_right


Output:

4.00000

Time Complexity: O(N * logN)
Auxiliary Space: O(N)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up
Recommended Articles
Page :