1 Count Problem

I tried implementing this question but I could only write the code to print the length of the longest sub array with 1s.
How am I supposed to print the new array after flipping k 0s?
LINK : https://ide.codingblocks.com/s/358552

hello @gptradhika1208

just use two variables one for storing the starting point of the sequence from where maxlen starts and one for storing the maximum length .

now use those variable to perform updation from 0 to 1.

this might help->

#include <iostream>
using namespace std;

void findZeros(int *arr, int n, int k) {
    int wL = 0, wR = 0, bestWindow = 0, zeroCount = 0, bestL = 0;
    while(wR < n) {
        if(zeroCount<=k) {
            if(arr[wR] == 0) 
                zeroCount++;
            wR++;
        } 
        if(zeroCount>k) {
            if(arr[wL] == 0) 
                zeroCount--;
            wL++;
        }
        if((wR-wL) > bestWindow and (zeroCount<=k)) {
            bestWindow = wR-wL;
            bestL = wL;
        }
    }
    // cout<<bestWindow<<","<<wR<<","<<wL<<","<<bestL<<endl;
    cout<<bestWindow<<endl;
    for(int i=0;i<bestL;i++) {
        cout<<arr[i]<<" ";
    }
    for(int i=bestL;i<bestL+bestWindow;i++) {
        if(arr[i]==0)
            arr[i]=1;
        cout<<arr[i]<<" ";
    }
    for(int i=bestL+bestWindow;i<n;i++) {
        cout<<arr[i]<<" ";
    }
}

int main(int argc, char const *argv[])
{
    /* code */
    int n, k;
    cin>>n>>k;
    int *arr = new int[n];
    for(int i=0;i<n;i++) {
        cin>>arr[i];
    }

    findZeros(arr, n, k);
    return 0;
}



I couldn’t really undertand the code. Can you please make changes in my code itself?

@gptradhika1208
refer this explanation ->
The idea is to use Sliding Window for the given array. Let us use a window covering from index wL to index wR. Let the number of zeros inside the window be zeroCount. We maintain the window with at most m zeros inside.

The main steps are:

  • While zeroCount is no more than m: expand the window to the right (wR++) and update the count zeroCount.
  • While zeroCount exceeds m, shrink the window from left (wL++), update zeroCount;
  • Update the widest window along the way. The positions of output zeros are inside the best window.

if still the code does not make sense then ping me back.

I tried to modify the code a bit but I’m still not getting the required output. The final value of pointer ‘r’ is coming out to be 0 and the length is also coming out to be incorrect. Please help me correct the errors. LINK : https://ide.codingblocks.com/s/358652

Please reply as soon as possible.

check now->

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.