Table of Contents

## Problem statement

In the problem ” Average Salary Excluding the Minimum and Maximum Salary” we are given a salary array. where each element in the array represents the salary of different employees. Each value in the array is unique.

Our task is to calculate the average salary of the employee excluding the minimum and the maximum salary.

## Example

Salary= [8000,9000,2000,3000,6000,1000]

4750.0

**Explanation:**

In the given salary array 9000 is the maximum salary and 1000 is the minimum salary. As we need to find the average salary excluding the minimum and maximum salary so we will not add these values to the total sum. The total sum is 19000 so the average is 19000/4 that is 4750.

## Approach

This is a basic math problem. Our task is to find the minimum and the maximum salary then find the average of the remaining salary. We will follow these steps:

- Initialize minimum salary with INT_MAX, the maximum salary with INT_MIN. We will use a variable to store the salary sum so initialize it with 0.
- Traverse the array and add each salary to the sum. Meanwhile, also update the value of the minimum salary and maximum salary.
- If the value of n is smaller than three then the average salary will be zero else average salary will be (total salary-the minimum salary-the maximum salary)/(n-2).
- We will multiply (n-2) with 1.0 because the average salary can be a double value.

## Code for Average Salary Excluding the Minimum and Maximum Salary Leetcode Solution

### C++ code

#include <bits/stdc++.h> using namespace std; double average(vector<int>& salary) { int n=salary.size(); int mn=INT_MAX,mx=INT_MIN,sum=0; for(int i=0;i<n;i++) { sum=sum+salary[i]; mn=min(mn,salary[i]); mx=max(mx,salary[i]); } double ans=(sum-mn-mx)/((n-2)*1.0); if(n>2) return ans; else return 0; } int main() { vector<int> arr = {8000,9000,2000,3000,6000,1000}; cout<<average(arr)<<endl; return 0; }

4750.0

### Java code

import java.util.Arrays; public class Tutorialcup { public static double average(int[] salary) { int n=salary.length; int mn=Integer.MAX_VALUE,mx=Integer.MIN_VALUE,sum=0; for(int i=0;i<n;i++) { sum=sum+salary[i]; mn=Math.min(mn,salary[i]); mx=Math.max(mx,salary[i]); } double ans=(sum-mn-mx)/((n-2)*1.0); if(n>2) return ans; else return 0; } public static void main(String[] args) { int [] arr = {8000,9000,2000,3000,6000,1000}; double ans= average(arr); System.out.println(ans); } }

4750.0

## Complexity Analysis of Average Salary Excluding the Minimum and Maximum Salary Leetcode Solution

### Time complexity

The time complexity of the above code is** O(n)** because we are traversing the salary array only once. Here n is the length of the salary array.

### Space complexity

The space complexity of the above code is **O(1)** because we are using only a variable to store answer.