1 count please check my code

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);
for (i = s; i < e; i++) {
a[i]=1;
}
for(i=0;i<n;i++) {
System.out.print(a[i]+" ");
}
}
}

for the test case:

7 0
0 1 0 0 0 1 0

you are getting

1
0 1 0 0 0 1 1

it should be

1
0 1 0 0 0 1 0

debug for this

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] + " "); } } }

PLEASE share your code after saving it on ide.codingblocks.com so thats it legible. Its not possible to check the code like this

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 :slight_smile: