Skip to content

Commit

Permalink
Add problem 1877: Minimize Maximum Pair Sum in Array
Browse files Browse the repository at this point in the history
  • Loading branch information
EFanZh committed Oct 10, 2023
1 parent 1bdfbdb commit 22c1baa
Show file tree
Hide file tree
Showing 3 changed files with 57 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1442,6 +1442,7 @@ pub mod problem_1861_rotating_the_box;
pub mod problem_1864_minimum_number_of_swaps_to_make_the_binary_string_alternating;
pub mod problem_1869_longer_contiguous_segments_of_ones_than_zeros;
pub mod problem_1876_substrings_of_size_three_with_distinct_characters;
pub mod problem_1877_minimize_maximum_pair_sum_in_array;

#[cfg(test)]
mod test_utilities;
38 changes: 38 additions & 0 deletions src/problem_1877_minimize_maximum_pair_sum_in_array/greedy.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
pub struct Solution;

// ------------------------------------------------------ snip ------------------------------------------------------ //

impl Solution {
pub fn min_pair_sum(nums: Vec<i32>) -> i32 {
let mut nums = nums;

nums.sort_unstable();

let mut nums = nums.as_slice();
let mut result = i32::MIN;

while let [first, rest @ .., last] = nums {
result = result.max(first + last);

nums = rest;
}

result
}
}

// ------------------------------------------------------ snip ------------------------------------------------------ //

impl super::Solution for Solution {
fn min_pair_sum(nums: Vec<i32>) -> i32 {
Self::min_pair_sum(nums)
}
}

#[cfg(test)]
mod tests {
#[test]
fn test_solution() {
super::super::tests::run::<super::Solution>();
}
}
18 changes: 18 additions & 0 deletions src/problem_1877_minimize_maximum_pair_sum_in_array/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
pub mod greedy;

pub trait Solution {
fn min_pair_sum(nums: Vec<i32>) -> i32;
}

#[cfg(test)]
mod tests {
use super::Solution;

pub fn run<S: Solution>() {
let test_cases = [(&[3, 5, 2, 3] as &[_], 7), (&[3, 5, 4, 2, 4, 6], 8)];

for (nums, expected) in test_cases {
assert_eq!(S::min_pair_sum(nums.to_vec()), expected);
}
}
}

0 comments on commit 22c1baa

Please sign in to comment.