import java.util.*;
public class Main {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int k = sc.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = sc.nextInt();
}
int i = 0, j, m = 0, s = -1, e = -1;
for (j = 0; j < a.length; ++j) {
if (a[j] == 0)
k–;
if (k < 0 && a[i++] == 0)
k++;
}
e = j;
s = i;
m = j - i;
System.out.println(m);
if (m != 1) {
for (i = s; i < e; i++) {
a[i] = 1;
}
}
for (i = 0; i < n; i++) {
System.out.print(a[i] + " ");
}
}
}
Still failing one count
your code logic is not correct.The idea is to use Sliding Window for the given array. The solution is taken from here. 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.
you can see this:
if this solves your doubt please mark it as resolved