Skip to content

Commit 98595e8

Browse files
committed
Add problem 3194: Minimum Average of Smallest and Largest Elements
1 parent a304b0a commit 98595e8

File tree

3 files changed

+58
-0
lines changed

3 files changed

+58
-0
lines changed

src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2130,6 +2130,7 @@ pub mod problem_3186_maximum_total_damage_with_spell_casting;
21302130
pub mod problem_3190_find_minimum_operations_to_make_all_elements_divisible_by_three;
21312131
pub mod problem_3191_minimum_operations_to_make_binary_array_elements_equal_to_one_i;
21322132
pub mod problem_3192_minimum_operations_to_make_binary_array_elements_equal_to_one_ii;
2133+
pub mod problem_3194_minimum_average_of_smallest_and_largest_elements;
21332134
pub mod problem_3350_adjacent_increasing_subarrays_detection_ii;
21342135

21352136
#[cfg(test)]
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
pub struct Solution;
2+
3+
// ------------------------------------------------------ snip ------------------------------------------------------ //
4+
5+
impl Solution {
6+
pub fn minimum_average(nums: Vec<i32>) -> f64 {
7+
let mut nums = nums.into_iter().map(i32::cast_unsigned).collect::<Vec<_>>();
8+
9+
nums.sort_unstable();
10+
11+
let (left, right) = nums.split_at(nums.len() / 2);
12+
13+
f64::from(
14+
left.iter()
15+
.zip(right.iter().rev())
16+
.fold(u32::MAX, |min, (&x, &y)| min.min(x + y)),
17+
) / 2.0
18+
}
19+
}
20+
21+
// ------------------------------------------------------ snip ------------------------------------------------------ //
22+
23+
impl super::Solution for Solution {
24+
fn minimum_average(nums: Vec<i32>) -> f64 {
25+
Self::minimum_average(nums)
26+
}
27+
}
28+
29+
#[cfg(test)]
30+
mod tests {
31+
#[test]
32+
fn test_solution() {
33+
super::super::tests::run::<super::Solution>();
34+
}
35+
}
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
pub mod iterative;
2+
3+
pub trait Solution {
4+
fn minimum_average(nums: Vec<i32>) -> f64;
5+
}
6+
7+
#[cfg(test)]
8+
mod tests {
9+
use super::Solution;
10+
11+
pub fn run<S: Solution>() {
12+
let test_cases = [
13+
(&[7, 8, 3, 4, 15, 13, 4, 1] as &[_], 5.5),
14+
(&[1, 9, 8, 3, 10, 5], 5.5),
15+
(&[1, 2, 3, 7, 8, 9], 5.0),
16+
];
17+
18+
for (nums, expected) in test_cases {
19+
approx::assert_ulps_eq!(S::minimum_average(nums.to_vec()), expected);
20+
}
21+
}
22+
}

0 commit comments

Comments
 (0)