algoadvance

Leetcode 1491. Average Salary Excluding the Minimum and Maximum Salary

Problem Statement:

You are given an array of unique integers salary where salary[i] is the salary of the ith employee.

Return the average salary of employees excluding the minimum and maximum salary. Answers within 10^-5 of the actual answer will be accepted.

Clarifying Questions:

  1. Q: What is the range of values for salary elements? A: Each element in salary is a positive integer.

  2. Q: How many elements are there in the salary array? A: There are at least three elements in the salary array.

  3. Q: What should be done if all elements in salary are the same? A: This scenario is not possible since all salaries need to be unique as per the problem statement.

Strategy:

To solve this problem:

  1. Identify the minimum and maximum salary in the array.
  2. Calculate the sum of all salaries.
  3. Subtract the minimum and maximum salary from the sum.
  4. Compute the average by dividing the resulting sum by the number of remaining elements (i.e., total elements minus two).

Code:

public class Solution {
    public double average(int[] salary) {
        // Initial variables to track the minimum and maximum salary
        int minSalary = Integer.MAX_VALUE;
        int maxSalary = Integer.MIN_VALUE;
        
        // Sum of all salaries
        int sumSalaries = 0;
        
        // Calculate the total sum and find min and max salaries
        for (int sal : salary) {
            if (sal < minSalary) {
                minSalary = sal;
            }
            if (sal > maxSalary) {
                maxSalary = sal;
            }
            sumSalaries += sal;
        }
        
        // Subtract min and max salary from the sum
        sumSalaries -= (minSalary + maxSalary);
        
        // Return the average excluding min and max salary
        return sumSalaries / (double)(salary.length - 2);
    }
}

Time Complexity:

The time complexity of this solution is O(n), where n is the number of elements in the salary array. This is because we iterate over the array a single time to find the sum, minimum, and maximum salaries.

Cut your prep time in half and DOMINATE your interview with AlgoAdvance AI