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 of k-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.
Example 1:
Input: nums = [0,1,0], k = 1 Output: 2 Explanation: Flip nums[0], then flip nums[2].
Example 2:
Input: nums = [1,1,0], k = 2 Output: -1 Explanation: No matter how we flip subarrays of size 2, we cannot make the array become [1,1,1].
Example 3:
Input: nums = [0,0,0,1,0,1,1,0], k = 3 Output: 3 Explanation: Flip nums[0],nums[1],nums[2]: nums becomes [1,1,1,1,0,1,1,0] Flip nums[4],nums[5],nums[6]: nums becomes [1,1,1,1,1,0,0,0] Flip nums[5],nums[6],nums[7]: nums becomes [1,1,1,1,1,1,1,1]
Constraints:
1 <= nums.length <= 105
1 <= k <= nums.length
We notice that the result of reversing several consecutive elements is independent of the order of the reversals. Therefore, we can greedily consider the number of reversals needed at each position.
We can process the array from left to right.
Suppose we need to process position
In this way, when we have processed all the elements in the array, we can return the answer.
The time complexity is
class Solution:
def minKBitFlips(self, nums: List[int], k: int) -> int:
n = len(nums)
d = [0] * (n + 1)
ans = s = 0
for i, x in enumerate(nums):
s += d[i]
if x % 2 == s % 2:
if i + k > n:
return -1
d[i] += 1
d[i + k] -= 1
s += 1
ans += 1
return ans
class Solution {
public int minKBitFlips(int[] nums, int k) {
int n = nums.length;
int[] d = new int[n + 1];
int ans = 0, s = 0;
for (int i = 0; i < n; ++i) {
s += d[i];
if (nums[i] % 2 == s % 2) {
if (i + k > n) {
return -1;
}
++d[i];
--d[i + k];
++s;
++ans;
}
}
return ans;
}
}
class Solution {
public:
int minKBitFlips(vector<int>& nums, int k) {
int n = nums.size();
int d[n + 1];
memset(d, 0, sizeof(d));
int ans = 0, s = 0;
for (int i = 0; i < n; ++i) {
s += d[i];
if (s % 2 == nums[i] % 2) {
if (i + k > n) {
return -1;
}
++d[i];
--d[i + k];
++s;
++ans;
}
}
return ans;
}
};
func minKBitFlips(nums []int, k int) int {
n := len(nums)
d := make([]int, n+1)
ans, s := 0, 0
for i, x := range nums {
s += d[i]
if s%2 == x%2 {
if i+k > n {
return -1
}
d[i]++
d[i+k]--
s++
ans++
}
}
return ans
}
function minKBitFlips(nums: number[], k: number): number {
const n = nums.length;
const d: number[] = Array(n + 1).fill(0);
let [ans, s] = [0, 0];
for (let i = 0; i < n; ++i) {
s += d[i];
if (s % 2 === nums[i] % 2) {
if (i + k > n) {
return -1;
}
d[i]++;
d[i + k]--;
s++;
ans++;
}
}
return ans;
}
impl Solution {
pub fn min_k_bit_flips(nums: Vec<i32>, k: i32) -> i32 {
let n = nums.len();
let mut d = vec![0; n + 1];
let mut ans = 0;
let mut s = 0;
for i in 0..n {
s += d[i];
if nums[i] % 2 == s % 2 {
if i + (k as usize) > n {
return -1;
}
d[i] += 1;
d[i + (k as usize)] -= 1;
s += 1;
ans += 1;
}
}
ans
}
}