Imagine you have a binary array where each element is either 0 or 1, and your goal is to make all elements become 1. However, you can't change individual bits - you can only perform k-bit flips!
A k-bit flip allows you to select any contiguous subarray of length k and flip every bit in it (0 becomes 1, 1 becomes 0). For example, if k=3 and you have [0,1,0,1,1], you could flip the first 3 elements to get [1,0,1,1,1].
Your mission: Find the minimum number of k-bit flips needed to make all elements equal to 1. If it's impossible, return -1.
Key Challenge: The order of operations matters! Flipping the same region twice cancels out, and you need to think strategically about which regions to flip to achieve the optimal solution.
Input & Output
Visualization
Time & Space Complexity
We scan the array once (O(n)) and for each 0, we may flip k elements (O(k))
We modify the array in-place, using only constant extra space
Constraints
- 1 โค nums.length โค 105
- 1 โค k โค nums.length
- nums[i] is either 0 or 1