Problem
You are given a binary array nums
and an integer k
.
A k-bit flip is choosing a subarray of length k
from nums
and simultaneously changing every 0
in the subarray to 1
, and every 1
in the subarray to 0
.
Return _the minimum number ofk-bit flips required so that there is no _0
in the array. If it is not possible, return -1
.
A subarray is a contiguous part of an array.
Examples
Example 1
|
|
Example 2
|
|
Example 3
|
|
Constraints
1 <= nums.length <= 10^5
1 <= k <= nums.length
Solution
Method 1 – Greedy with Flip Count (Sliding Window)
Intuition
We want to flip only when we see a 0, and each flip affects k consecutive bits. To avoid flipping the same bit multiple times, use a sliding window to track flips and propagate their effect.
Approach
- Iterate through nums. If the current bit is 0 (after considering previous flips), flip starting here.
- Use a variable to track the number of flips affecting the current position.
- Use an auxiliary array to mark where flips end.
- If a flip would go out of bounds, return -1.
- Count total flips.
Code
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n)
— n = length of nums. - 🧺 Space complexity:
O(n)
— for flip tracking array.