Minimum Number of K Consecutive Bit Flips LeetCode solution in C++

1
class Solution {
2
public:
3
int minKBitFlips(vector<int> &nums, int k) {
4
int n = nums.size();
5

6
int flips = 0; // flips on current positions
7
vector<int> flip(n + 1, 0); // to set end pointer for a flip i.e i+k ->-1
8
int ops = 0; // answer
9

10
for (int i = 0; i < n; i++) {
11
flips += flip[i]; // update flips for current position
12

13
// even flips on 1 okay
14
if (nums[i] == 1 && (flips) % 2 == 0) {
15
continue;
16
}
17

18
// odd flips on 0 okay
19

20
if (nums[i] == 0 && (flips) % 2 != 0) {
21
continue;
22
}
23

24
// margin error as k bits flips is must
25

26
if (i + k > n) {
27
return -1;
28
}
29

30
ops++; // increment ans
31
flips++; // do flip at this position
32
flip[i + k] = -1; // set poiter where current flip ends
33
}
34

35
return ops;
36
}
37
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0