Tuesday, March 9, 2021

Published March 09, 2021 by Anonymous with 0 comment

Minimize flips on K-length subarrays required to make all array elements equal to 1

#include <bits/stdc++.h>

using namespace std;

  

void minimumOperations(vector<int>& A, int K)

{

    

    

    vector<int> isflipped(A.size(), 0);

  

    

    int ans = 0;

  

    

    for (int i = 0; i < A.size(); i++) {

  

        

        

        if (i > 0) {

            isflipped[i] += isflipped[i - 1];

            isflipped[i] %= 2;

        }

  

        

        

        if (A[i] == 0 && !isflipped[i]) {

  

            

            

            

            if ((A.size() - i + 1) <= K) {

                cout << -1;

                return;

            }

  

            

            ans++;

  

            

            

            isflipped[i]++;

  

            

            isflipped[i + K]--;

        }

        else if (A[i] == 1 && isflipped[i]) {

  

            

            

            

            if ((A.size() - i + 1) <= K) {

                cout << -1;

                return;

            }

  

            

            ans++;

  

            

            

            isflipped[i]++;

  

            

            isflipped[i + K]--;

        }

    }

  

    

    cout << ans;

}

  

int main()

{

    vector<int> arr = { 0, 1, 0 };

    int K = 1;

    minimumOperations(arr, K);

  

    return 0;

}

Let's block ads! (Why?)

      edit

0 comments:

Post a Comment