Skip to content

Commit 152d67e

Browse files
committed
Add problem 3012: Minimize Length of Array Using Operations
1 parent 12f71dc commit 152d67e

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
@@ -2046,6 +2046,7 @@ pub mod problem_3001_minimum_moves_to_capture_the_queen;
20462046
pub mod problem_3005_count_elements_with_maximum_frequency;
20472047
pub mod problem_3010_divide_an_array_into_subarrays_with_minimum_cost_i;
20482048
pub mod problem_3011_find_if_array_can_be_sorted;
2049+
pub mod problem_3012_minimize_length_of_array_using_operations;
20492050

20502051
#[cfg(test)]
20512052
mod test_utilities;
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
pub struct Solution;
2+
3+
// ------------------------------------------------------ snip ------------------------------------------------------ //
4+
5+
use std::num::NonZero;
6+
7+
impl Solution {
8+
pub fn minimum_array_length(nums: Vec<i32>) -> i32 {
9+
let nums = nums.into_iter().map(i32::cast_unsigned).collect::<Vec<_>>();
10+
let min = NonZero::new(nums.iter().copied().fold(u32::MAX, u32::min)).unwrap();
11+
let mut min_count = 0;
12+
13+
for &num in &nums {
14+
if num % min != 0 {
15+
return 1;
16+
}
17+
18+
min_count += u32::from(num == min.get());
19+
}
20+
21+
min_count.div_ceil(2).cast_signed()
22+
}
23+
}
24+
25+
// ------------------------------------------------------ snip ------------------------------------------------------ //
26+
27+
impl super::Solution for Solution {
28+
fn minimum_array_length(nums: Vec<i32>) -> i32 {
29+
Self::minimum_array_length(nums)
30+
}
31+
}
32+
33+
#[cfg(test)]
34+
mod tests {
35+
#[test]
36+
fn test_solution() {
37+
super::super::tests::run::<super::Solution>();
38+
}
39+
}
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
pub mod greedy;
2+
3+
pub trait Solution {
4+
fn minimum_array_length(nums: Vec<i32>) -> i32;
5+
}
6+
7+
#[cfg(test)]
8+
mod tests {
9+
use super::Solution;
10+
11+
pub fn run<S: Solution>() {
12+
let test_cases = [(&[1, 4, 3, 1] as &[_], 1), (&[5, 5, 5, 10, 5], 2), (&[2, 3, 4], 1)];
13+
14+
for (nums, expected) in test_cases {
15+
assert_eq!(S::minimum_array_length(nums.to_vec()), expected);
16+
}
17+
}
18+
}

0 commit comments

Comments
 (0)