Skip to content

Commit 30c6591

Browse files
committed
Add problem 3375: Minimum Operations to Make Array Values Equal to K
1 parent 4b9b4ec commit 30c6591

3 files changed

Lines changed: 62 additions & 0 deletions

File tree

src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2207,6 +2207,7 @@ pub mod problem_3364_minimum_positive_sum_subarray;
22072207
pub mod problem_3365_rearrange_k_substrings_to_form_target_string;
22082208
pub mod problem_3370_smallest_number_with_all_set_bits;
22092209
pub mod problem_3371_identify_the_largest_outlier_in_an_array;
2210+
pub mod problem_3375_minimum_operations_to_make_array_values_equal_to_k;
22102211

22112212
#[cfg(test)]
22122213
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::cmp::Ordering;
6+
7+
impl Solution {
8+
pub fn min_operations(nums: Vec<i32>, k: i32) -> i32 {
9+
let nums = nums.into_iter().map(i32::cast_unsigned).collect::<Vec<_>>();
10+
let k = k.cast_unsigned();
11+
let mut masks = [0_usize; 101_usize.div_ceil(usize::BITS as usize)];
12+
13+
for num in nums {
14+
match num.cmp(&k) {
15+
Ordering::Less => return -1,
16+
Ordering::Equal => {}
17+
Ordering::Greater => masks[(num / usize::BITS) as usize] |= 1 << (num % usize::BITS),
18+
}
19+
}
20+
21+
masks.iter().copied().map(usize::count_ones).sum::<u32>().cast_signed()
22+
}
23+
}
24+
25+
// ------------------------------------------------------ snip ------------------------------------------------------ //
26+
27+
impl super::Solution for Solution {
28+
fn min_operations(nums: Vec<i32>, k: i32) -> i32 {
29+
Self::min_operations(nums, k)
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: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
pub mod bit_masks;
2+
3+
pub trait Solution {
4+
fn min_operations(nums: Vec<i32>, k: 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 = [
13+
((&[5, 2, 5, 4, 5] as &[_], 2), 2),
14+
((&[2, 1, 2], 2), -1),
15+
((&[9, 7, 5, 3], 1), 4),
16+
];
17+
18+
for ((nums, k), expected) in test_cases {
19+
assert_eq!(S::min_operations(nums.to_vec(), k), expected);
20+
}
21+
}
22+
}

0 commit comments

Comments
 (0)