LeetCode 1491: Average Salary Excluding the Minimum and Maximum Salary

ArraySorting

Problem Description

Explanation:

To find the average salary excluding the minimum and maximum salary, we can first find the minimum and maximum salaries in the array. Then, we iterate through the array to calculate the sum of all salaries excluding the minimum and maximum salaries. Finally, we divide the sum by the number of employees minus 2 to get the average salary.

  1. Find the minimum and maximum salaries in the array.
  2. Iterate through the array to calculate the sum of all salaries excluding the minimum and maximum.
  3. Calculate the average salary by dividing the sum by the number of employees minus 2.

Time Complexity: O(n) where n is the number of elements in the salary array.

Space Complexity: O(1)

:

Solutions

class Solution {
    public double average(int[] salary) {
        int min = Integer.MAX_VALUE, max = Integer.MIN_VALUE;
        double sum = 0;
        
        for (int s : salary) {
            sum += s;
            min = Math.min(min, s);
            max = Math.max(max, s);
        }
        
        return (sum - min - max) / (salary.length - 2);
    }
}

Loading editor...