Problem
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.
Examples
Example 1:
|
|
Example 2:
|
|
Constraints:
3 <= nums.length <= 10^5
0 <= nums[i] <= 1
Solution
Method 1 - Greedy
Here is the approach:
- Use a greedy strategy to process the array from left to right. Start flipping at the first occurrence of
0
because flipping is only needed if an element is0
. - Each flip can affect up to three consecutive elements. Therefore:
- When encountering a
0
at positioni
, flip elements at positionsi
,i+1
, andi+2
. - If
i+2
exceeds the boundary of the array (i.e., not enough elements for a complete flip), transformation becomes impossible, and return-1
.
- When encountering a
- After processing the entire array, verify if all elements in
nums
are1
. If not, return-1
.
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n)
, wheren
is the size of the array. The array is traversed once, flipping elements when necessary. - 🧺 Space complexity:
O(1)
. No extra space is used; modifications are made in-place.