Determine the minimum number of contiguous flip operations needed to turn every element in a binary array into 1.
You are given a binary array containing only 0 and 1.
In one operation, you may choose a starting index and flip a length-3 subarray starting at , changing each of its elements from 0 to 1 or from 1 to 0.
Return the minimum number of operations needed to make every element in the array equal to 1. If it is impossible, return -1.
You should reason about the array from left to right and decide when a flip is forced by the current value.
nums.Return the minimum number of operations required to make all elements 1, or -1 if it cannot be done.
1 <= nums.lengthnums[i] is either 0 or 1Example 1
Input
nums = [0,1,0,1,0,1,0]
Output
3
Explanation
Flip at index 0 -> [1,0,1,1,0,1,0]. Flip at index 1 -> [1,1,0,0,0,1,0]. Flip at index 4 -> [1,1,0,0,1,0,1]. A better sequence exists with 3 flips total, and fewer is not possible.
Example 2
Input
nums = [1,1,1]
Output
0
Explanation
The array is already all ones.
Example 3
Input
nums = [0,0]
Output
-1
Explanation
No length-3 flip can be applied, so it is impossible to make all elements equal to 1.
Premium problem context
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.