Find zeroes to be flipped so that number of consecutive 1's is maximized
Input: arr[] = {1, 0, 0, 1, 1, 0, 1, 0, 1, 1, 1} m = 2 Output: 5 7 We are allowed to flip maximum 2 zeroes. If we flip arr[5] and arr[7], we get 8 consecutive 1's which is maximum possible under given constraints Input: arr[] = {1, 0, 0, 1, 1, 0, 1, 0, 1, 1, 1} m = 1 Output: 7 We are allowed to flip maximum 1 zero. If we flip arr[7], we get 5 consecutive 1's which is maximum possible under given constraints. Input: arr[] = {0, 0, 0, 1} m = 4 Output: 0 1 2 Since m is more than number of zeroes, we can flip all zeroes.
Steps:
It is based on sliding window method.
The window at any time should consists of only m zeroes.
If the zerocount is below m wr is incremented.
If the zerocount is more wl is incremented.
Code:
import java.util.*;
public class Solution {
public static void main(String[] args) {
int[] a = {1,1,0,1,1,0,0,1,1,1};
int m = 2;
int n = a.length;
int zerocount = 0;
int wr = 0, wl=0;
int bestl = 0, bestr = 0, size = 0;
int check = 0;
while(wr<n){
if(zerocount <= m){
if(a[wr] == 0)
zerocount++;
wr++;
}
if(zerocount > m){
if(a[wl] == 0)
zerocount--;
wl++;
}
if( wr - wl > size){
size = wr - wl;
bestl = wl;
bestr = wr;
}
}
for(int i=bestl; i<bestr; i++){
if(a[i] == 0){
System.out.print(i+" ");
}
}
}
}
Output:
5 6
Illustration:
https://www.geeksforgeeks.org/window-sliding-technique/
https://www.geeksforgeeks.org/find-zeroes-to-be-flipped-so-that-number-of-consecutive-1s-is-maximized/
Comments
Post a Comment