Skip to content

Commit 1a4ad1c

Browse files
committed
Add problem 3191: Minimum Operations to Make Binary Array Elements Equal to One I
1 parent af836f0 commit 1a4ad1c

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
@@ -2128,6 +2128,7 @@ pub mod problem_3184_count_pairs_that_form_a_complete_day_i;
21282128
pub mod problem_3185_count_pairs_that_form_a_complete_day_ii;
21292129
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;
2131+
pub mod problem_3191_minimum_operations_to_make_binary_array_elements_equal_to_one_i;
21312132
pub mod problem_3350_adjacent_increasing_subarrays_detection_ii;
21322133

21332134
#[cfg(test)]
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+
impl Solution {
6+
pub fn min_operations(nums: Vec<i32>) -> i32 {
7+
let mut mask = 0_u32;
8+
let mut result = 0;
9+
10+
for num in nums {
11+
let num = num.cast_unsigned() ^ (mask & 1);
12+
13+
mask >>= 1;
14+
15+
if num == 0 {
16+
mask ^= 3;
17+
result += 1;
18+
}
19+
}
20+
21+
if mask == 0 { result } else { -1 }
22+
}
23+
}
24+
25+
// ------------------------------------------------------ snip ------------------------------------------------------ //
26+
27+
impl super::Solution for Solution {
28+
fn min_operations(nums: Vec<i32>) -> i32 {
29+
Self::min_operations(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 min_operations(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 = [(&[0, 1, 1, 1, 0, 0] as &[_], 3), (&[0, 1, 1, 1], -1)];
13+
14+
for (nums, expected) in test_cases {
15+
assert_eq!(S::min_operations(nums.to_vec()), expected);
16+
}
17+
}
18+
}

0 commit comments

Comments
 (0)