Minimum Number of K Consecutive Bit Flips
You are given a binary array nums and an integer k.
In one operation, you can choose any contiguous subarray of length k and flip all its bits:
- change every 0 to 1
- change every 1 to 0
Return the minimum number of such operations needed to make every element of nums equal to 1.
If it is not possible, return -1.
Example 1:
Input: nums = [0,1,0,1], k = 2
Output: 2
Explanation:
- Flip the subarray from index 0 to 1: [0,1,0,1] -> [1,0,0,1]
- Flip the subarray from index 1 to 2: [1,0,0,1] -> [1,1,1,1]
So, the minimum number of flips required is 2.
Example 2:
Input: nums = [0,0,1,0], k = 3
Output: -1
Explanation:
- Flip the subarray from index 0 to 2: [0,0,1,0] -> [1,1,0,0]
Now the remaining 0s cannot be fixed using any subarray of length 3, so the answer is -1.
Now Your Turn!
Pick the correct output for the given inputInput: nums = [1,0,0,1,0], k = 2
Still unsure what the problem is asking ?
Let’s go through a few more examples, step by step, to make it clearer.
Constraints:
- 1 <= nums.length <= 105
- nums[i] is either 0 or 1
- 1 <= k <= nums.length