Leetcode 1619. Mean of Array After Removing Some Elements
The problem is to find the mean of an array after removing some elements. Specifically, you are to remove the smallest 5% and the largest 5% of the elements, and then calculate the mean of the remaining elements.
Below is the C++ solution for the given problem:
#include <vector>
#include <algorithm>
#include <numeric>
class Solution {
public:
double trimMean(std::vector<int>& arr) {
int n = arr.size();
int removeCount = n * 0.05; // 5% of the size
// Sort the array
std::sort(arr.begin(), arr.end());
// Calculate the sum of the remaining array after removing smallest and largest 5%
double sum = 0;
for (int i = removeCount; i < n - removeCount; ++i) {
sum += arr[i];
}
// Calculate the new length after removal
int newLength = n - 2 * removeCount;
// Calculate and return the mean
return sum / newLength;
}
};
removeCount
to n - removeCount
to sum the middle portion of the array.To verify the correctness of the solution, consider the following test cases:
Example:
int main() {
Solution sol;
std::vector<int> arr1 = {1,2,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20};
std::cout << sol.trimMean(arr1) << std::endl; // Expected output: mean after removing 5% smallest and largest elements
return 0;
}
Be sure to customize the test cases based on the mean of the results after removing the 5% of smallest and largest elements.
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?