#3191
Medium Algorithms Minimum operations to make binary array elements equal to one i
Array Bit Manipulation Queue Sliding Window Prefix Sum
80.4% acceptance
Feb 24, 2026
673
36
You are given a binary array nums.
You can do the following operation on the array any number of times (possibly zero):
Choose any 3 consecutive elements from the array and flip all of them.
Flipping an element means changing its value from 0 to 1, and from 1 to 0.
Return the minimum number of operations required to make all elements in nums equal to 1.
If it is impossible, return -1.
Solution
Rust
Time O(n)
Space O(1)
impl Solution {
pub fn min_operations(nums: Vec<i32>) -> i32 {
let n = nums.len();
let mut nums = nums;
let mut ops = 0;
for i in 0..n - 2 {
if nums[i] == 0 {
nums[i] ^= 1;
nums[i + 1] ^= 1;
nums[i + 2] ^= 1;
ops += 1;
}
}
if nums[n - 2] == 1 && nums[n - 1] == 1 {
ops
} else {
-1
}
}
}