Skip to content

Commit cafbf05

Browse files
authored
Create average-salary-excluding-the-minimum-and-maximum-salary.cpp
1 parent b6f75ec commit cafbf05

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
// Time: O(n)
2+
// Space: O(1)
3+
4+
// one-pass solution
5+
class Solution {
6+
public:
7+
double average(vector<int>& salary) {
8+
int total = 0;
9+
int mi = numeric_limits<int>::max(), ma = numeric_limits<int>::min();
10+
for (const auto& s : salary) {
11+
total += s;
12+
mi = min(mi, s), ma = max(ma, s);
13+
}
14+
return double(total - mi - ma) / (salary.size() - 2);
15+
}
16+
};
17+
18+
// Time: O(n)
19+
// Space: O(1)
20+
// one-liner solution
21+
class Solution2 {
22+
public:
23+
double average(vector<int>& salary) {
24+
return (accumulate(cbegin(salary), cend(salary), 0.0) -
25+
*min_element(cbegin(salary), cend(salary)) -
26+
*max_element(cbegin(salary), cend(salary)))
27+
/ (salary.size() - 2);
28+
}
29+
};

0 commit comments

Comments
 (0)