please give me some hint
How can i approach this problem?
use the approach of Sliding Window for the given array. use a window covering from index Left to index Right. Let the number of zeros inside the window be zeroCount. We maintain the window with at most m zeros inside.
- While zeroCount is no more than m: expand the window to the right and update the count zeroCount.
- While zeroCount exceeds m, shrink the window from left , update zeroCount;
- Update the widest window along the way. The positions of output zeros are inside the best window.
i am applying same approach but not passing all test cases
import java.util.*;
public class Main {
public static long count(int arr[], int k){
int n=arr.length;
int left=0;
int zero=0;
long max_len=0;
for(int right=0;right<n;right++){
if(arr[right]==0){
zero++;
}
while(zero>k){
if(arr[left]==0)
zero--;
left++;
}
max_len=Math.max(max_len,right-left+1);
}
return max_len;
}
public static void main(String args[]) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int k=sc.nextInt();
int arr[]=new int[n];
for(int i=0;i<n;i++){
arr[i]=sc.nextInt();
}
System.out.println(count(arr,k));
}
}
print the Array after flipping k 0s too in second line
how can i know which zero need to flip??
you are updating the window to find a way such that the positions of output zeros are inside the best window. and you print the count there .
just print this array after final change