classSolution { public: intminKBitFlips(vector<int>& A, int K){ int n = A.size(), flipped = 0, ans = 0; vector<int> isFlipped(n); for (int i = 0; i < n; ++i) { if (i >= K) flipped ^= isFlipped[i - K]; if (flipped == A[i]) { if (i + K > n) return-1; isFlipped[i] = 1; flipped ^= 1; ++ans; } } return ans; } };
classSolution { public: intminKBitFlips(vector<int>& A, int K){ int n = A.size(), flipped = 0, ans = 0; queue<int> isFlipped; for (int i = 0; i < n; ++i) { if (i >= K) { flipped ^= isFlipped.front(); isFlipped.pop(); } if (flipped == A[i]) { if (i + K > n) return-1; isFlipped.push(1); flipped ^= 1; ++ans; } else { isFlipped.push(0); } } return ans; } };
classSolution { public: intminKBitFlips(vector<int>& A, int K){ // "cur" is the count of flipping times within current sliding window. int n = A.size(), cur = 0, ans = 0; for (int i = 0; i < n; ++i) { if (i >= K && A[i - K] > 1) { --cur; A[i - K] += 2; } if (cur % 2 == A[i]) { if (i + K > n) return-1; A[i] += 2; ++cur; ++ans; } } return ans; } };