20241018 finished.

This commit is contained in:
jackfiled 2024-10-18 14:38:52 +08:00
parent 1c02ce3073
commit be822927b6
2 changed files with 64 additions and 1 deletions

View File

@ -267,3 +267,4 @@ mod p887_super_egg_drop;
mod p3200_maximum_height_of_a_triangle;
mod p3194_minimum_average_of_smallest_and_largest_elements;
mod p3193_count_the_number_of_inversions;
mod p3191_minimum_operations_to_make_binary_array_elements_equal_to_one_i;

View File

@ -0,0 +1,62 @@
/**
* [3191] Minimum Operations to Make Binary Array Elements Equal to One I
*/
pub struct Solution {}
// submission codes start here
impl Solution {
pub fn min_operations(nums: Vec<i32>) -> i32 {
let mut result = 0;
let mut nums = nums;
let mut pos = 0;
while pos < nums.len() - 3 {
if nums[pos] == 1 {
pos += 1;
continue;
}
nums[pos] = 1;
Self::reverse(pos + 1, &mut nums);
Self::reverse(pos + 2, &mut nums);
result += 1;
pos += 1;
}
if nums[pos] ^ nums[pos + 1] == 0 && nums[pos + 1] ^ nums[pos + 2] == 0 {
if nums[pos] == 1 {
result
} else {
result + 1
}
} else {
-1
}
}
fn reverse(pos: usize, nums: &mut Vec<i32>) {
nums[pos] = if nums[pos] == 1 {
0
} else {
1
}
}
}
// submission codes end
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_3191() {
assert_eq!(-1, Solution::min_operations(vec![0, 1, 1, 0, 1, 0, 0]));
assert_eq!(3, Solution::min_operations(vec![0, 1, 1, 1, 0, 0]));
assert_eq!(-1, Solution::min_operations(vec![0, 1, 1, 1]));
}
}