In this approach, I iterate through the array and flip the first encountered '0' along with the next two elements. This ensures I always maximize the number of '1's as it moves forward. If any '0' remains in the last two positions, it is impossible to make all elements '1'.
class Solution:
def minOperations(self, nums: List[int]) -> int:
n = len(nums)
operations = 0
for i in range(n - 2):
if nums[i] == 0:
nums[i] ^= 1
nums[i + 1] ^= 1
nums[i + 2] ^= 1
operations += 1
if nums[-2] == 0 or nums[-1] == 0:
return -1
return operations
- Time: O(n)
- Space: O(1)
