Minimum Number of K Consecutive Bit Flips in C++

C++Server Side ProgrammingProgramming

Suppose we have an array A. This is containing only 0s and 1s, here a K-bit flip consists of choosing a (contiguous) subarray of length K and simultaneously inverting the bits n the subarray. We have to find the minimum number of K-bit flips required so that there is no 0 in the array. If there is no such possibility, then return -1.

So, if the input is like [0,0,0,1,0,1,1,0] and K = 3, then the output will be 3, as we need to perform the operations three times, on the first try flip A[0] to A[3], the array will be [1,1,1,1,0,1,1,0], on the second run flip A[4] to A[6], the array will be [1,1,1,1,1,0,0,0], and in the 3rd move change A[5] to A[7], the array will be [1,1,1,1,1,1,1,1].

To solve this, we will follow these steps −

  • n := size of A

  • Define an array moves of size n

  • counter := 0

  • for initialize i := 0, when i + K <= n, update (increase i by 1), do −

    • if i > 0, then −

      • moves[i] := moves[i] + moves[i - 1]

    • if not ((moves[i] mod 2) + A[i]) mod 2 is non-zero, then −

      • moves[i] := moves[i] + 1

      • if i + K < n, then −

        • moves[i + K] - = 1

      • (increase counter by 1)

  • for i < n, update (increase i by 1), do −

    • if i > 0, then −

      • moves[i] := moves[i] + moves[i - 1]

    • if not ((moves[i] mod 2) + A[i]) mod 2 is non-zero, then −

      • return -1

  • return counter

Let us see the following implementation to get better understanding −

Output

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
   public:
   int minKBitFlips(vector<int>& A, int K){
      int n = A.size();
      vector<int> moves(n);
      int i;
      int counter = 0;
      for (i = 0; i + K <= n; i++) {
         if (i > 0)
         moves[i] += moves[i - 1];
         if (!(((moves[i] % 2) + A[i]) % 2)) {
            moves[i] += 1;
            if (i + K < n)
               moves[i + K] -= 1;
            counter++;
         }
      }
      for (; i < n; i++) {
         if (i > 0)
         moves[i] += moves[i - 1];
         if (!(((moves[i] % 2) + A[i]) % 2))
            return -1;
      }
      return counter;
   }
};
main(){
   Solution ob;
   vector<int> v = {0,0,0,1,0,1,1,0};
   cout << (ob.minKBitFlips(v, 3));
}

Input

{0,0,0,1,0,1,1,0}, 3

Output

3
raja
Published on 04-Jun-2020 09:45:33
Advertisements