1491-Average-Salary-Excluding-the-Minimum-and-Maximum-Salary

1491-Average-Salary-Excluding-the-Minimum-and-Maximum-Salary

Question

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.

Solution

遍历相加总量并记录最小值和最大值。

减去最大值及最大值,然后返回平均数即可。

We traverse through the values, add them together and record the minimum and maximum values.

Next we subtract the maximum value and the minimum value from the sum, and then return the average value.

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public double average(int[] salary) {
double total = 0, min = Integer.MAX_VALUE, max = Integer.MIN_VALUE;
for(int i = 0; i < salary.length; i++){
total += salary[i];
if(salary[i] > max){
max = salary[i];
}
if(salary[i] < min){
min = salary[i];
}
}
total -= min;
total -= max;
return total / (salary.length - 2);
}
}
Author

Xander

Posted on

2023-04-30

Updated on

2023-04-30

Licensed under

Comments