Skip to content

Commit

Permalink
Add problem 2341: Maximum Number of Pairs in Array
Browse files Browse the repository at this point in the history
  • Loading branch information
EFanZh committed Nov 28, 2024
1 parent a16819c commit 17971c9
Show file tree
Hide file tree
Showing 3 changed files with 59 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 @@ -1736,6 +1736,7 @@ pub mod problem_2331_evaluate_boolean_binary_tree;
pub mod problem_2335_minimum_amount_of_time_to_fill_cups;
pub mod problem_2336_smallest_number_in_infinite_set;
pub mod problem_2337_move_pieces_to_obtain_a_string;
pub mod problem_2341_maximum_number_of_pairs_in_array;

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

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

impl Solution {
pub fn number_of_pairs(nums: Vec<i32>) -> Vec<i32> {
let n = nums.len() as u8;
let mut seen = 0_u128;
let mut pairs = 0;

for num in nums {
let probe = 1 << (num as u8);

pairs += u8::from((seen & probe) != 0);
seen ^= probe;
}

vec![i32::from(pairs), i32::from(n - pairs * 2)]
}
}

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

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

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

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

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

pub fn run<S: Solution>() {
let test_cases = [
(&[1, 3, 2, 1, 3, 2, 2] as &[_], [3, 1]),
(&[1, 1], [1, 0]),
(&[0], [0, 1]),
];

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

0 comments on commit 17971c9

Please sign in to comment.