topic
text
In the array A containing only 0 and 1, a K bit flip involves selecting a (contiguous) sub-array of length K, and changing each 0 in the sub-array to 1 and changing each 1 to 0.
Returns the minimum number of K bit flips required so that the array has no elements with value 0. If it is not possible, return -1.
Example 1:
Input: A = [0,1,0], K = 1
Output: 2
Explanation: First flip A[0], then flip A[2].
Example 2:
Input: A = [1,1,0], K = 2
Output: -1
Explanation: No matter how we flip the sub-array of size 2, we cannot make the array [1,1,1].
Example 3:
Input: A = [0,0,0,1,0,1,1,0], K = 3
Output: 3
Explanation:
Flip A[0],A[1],A[2]: A becomes [ 1,1,1,1,0,1,1,0]
flip A[4],A[5],A[6]: A becomes [1,1,1,1,1,0,0, 0]
Flip A[5], A[6], A[7]: A becomes [1,1,1,1,1,1,1,1]
prompt:
1 <= A.length <= 30000
1 <= K <= A.length
Source: LeetCode
template
int minKBitFlips(int* A, int ASize, int K){
}
Problem solving
analysis
The requirement of the title is to flip a K-length sub-array (0->1,1->0) for an array composed of a known 01, and find the minimum number of times to flip until all elements are 1, if this goal cannot be achieved Just return -1;
this question is applied to many methods: such as greedy algorithm, difference, sliding window.
how are you:
What we want to flip is a small window of length K, which can be flipped, flipping twice equals not flipping.
Sliding window:
Judging from doing so, whether each element needs to be flipped.
Difference array:
If you need to flip, record the number of flips. The record is the first bit (i) of the differential traversal plus, and the last bit (i+k) minus. Finally, use the difference to find the cumulative number of flips;
if you need to flip, but the length of the remaining elements is less than K, then it is impossible to complete the goal of setting all 1, just return -1.
coding
Definition and initialization
Here is the definition of the establishment and initialization of the difference array, and the definition of the number of reversals that need to be returned at the end. For revCnt, it is counted as the first diff[i] of our difference array;
int diff[ASize + 1];
memset(diff, 0, sizeof(diff));
int ans = 0, revCnt = 0;
Build traversal
for (int i = 0; i < ASize; ++i) {
}
revCnt is bound to diff[i]
revCnt += diff[i];
Determine whether you need to flip and determine the subsequent length
if ((A[i] + revCnt) % 2 == 0) {
if (i + K > ASize) {
return -1;
}
}
If you flip to perform an operation
++ans;
++revCnt;
--diff[i + K];
Complete code
int minKBitFlips(int* A, int ASize, int K) {
int diff[ASize + 1];
memset(diff, 0, sizeof(diff));
int ans = 0, revCnt = 0;
for (int i = 0; i < ASize; ++i) {
revCnt += diff[i];
if ((A[i] + revCnt) % 2 == 0) {
if (i + K > ASize) {
return -1;
}
++ans;
++revCnt;
--diff[i + K];
}
}
return ans;
}