Program to Compute Average excluding Largest and Smallest Values
Program to Compute Average excluding Largest and Smallest Values
Description:
Given an array arr[] of integers, write a program to compute the average value of the array, excluding the largest and smallest values.
Input: arr = {2, 6, 4, 9, 1, 5}
Output: Average excluding largest and smallest values: 4
Explanation: The array is {2, 6, 4, 9, 1, 5}, and after excluding the largest value 9 and the smallest value 1, the remaining values are {2, 6, 4, 5}. The average of these values is (2 + 6 + 4 + 5) / 4 = 4.
Constraints:
The array length |arr| is at least 3 and at most 10^5. Elements in the array are integers ranging from -10^9 to 10^9.
Java Code:
import java.util.Arrays; public class HackerAlgo { // Compute Average excluding Largest and Smallest Values public static double computeAverage(int[] arr) { int n = arr.length; if (n < 3) { System.out.println("Array length should be at least 3 for computing average."); return 0.0; } Arrays.sort(arr); double sum = 0; for (int i = 1; i< n - 1; i++) { sum += arr[i]; } return sum / (n - 2); } public static void main(String[] args) { // Example for Compute Average excluding Largest and Smallest Values int[] arr = {2, 6, 4, 9, 1, 5}; double result = computeAverage(arr); System.out.println("Average excluding largest and smallest values: " + result
Python Code:
# Compute Average excluding Largest and Smallest Values def compute_average(arr): n = len(arr) if n < 3: print("Array length should be at least 3 for computing average.") return 0.0 arr.sort() return sum(arr[1:-1]) / (n - 2) # Example usage arr = [2, 6, 4, 9, 1, 5] result = compute_average(arr) print("Average excluding largest and smallest values:", result)
C++ Code:
#include <iostream> #include <vector> #include <algorithm> class HackerAlgo { public: // Compute Average excluding Largest and Smallest Values static double computeAverage(std::vector<int>& arr) { int n = arr.size(); if (n < 3) { std::cout<< "Array length should be at least 3 for computing average." <<std::endl; return 0.0; } std::sort(arr.begin(), arr.end()); double sum = 0; for (int i = 1; i< n - 1; i++) { sum += arr[i]; } return sum / (n - 2); } }; int main() { // Example for Compute Average excluding Largest and Smallest Values std::vector<int>arr = {2, 6, 4, 9, 1, 5}; double result = HackerAlgo::computeAverage(arr); std::cout<< "Average excluding largest and smallest values: " << result << std::endl; return 0
JavaScript Code:
class HackerAlgo { // Compute Average excluding Largest and Smallest Values static computeAverage(arr) { const n = arr.length; if (n < 3) { console.log("Array length should be at least 3 for computing average."); return 0.0; } arr.sort((a, b) => a - b); const sum = arr.slice(1, -1).reduce((acc, num) =>acc + num, 0); return sum / (n - 2); } } // Example usage constarr = [2, 6, 4, 9, 1, 5]; const result = HackerAlgo.computeAverage(arr); console.log("Average excluding largest and smallest values:", result);