geeksforgeeks:findFind zeroes to be flipped so that number of consecutive 1’s is maximized
Given a binary array and an integer m, find the position of zeroes flipping which creates maximum number of consecutive 1’s in array.
Examples :
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.
Input: arr[] = {0 , 0, 0, 0, 0} m = 2
Solution: sliding window
use a window covering from the wL to wR. Let variable zeroCount to count the zero numbers inside the window.
If zero count of the current window is less than m, wide the window to right.
update the widest window if current window is more.
if the right reach the end of the length, quit the while.
reduce the left 0 count in order to wide current window in right.(reduce 1, then reduce 0 in left)
static int findLongestStreak2(int[] a, int m) { int right = 0; int left = 0; int zeros = 0; int maxStreak = 0; int maxL = 0; int streak = 0; while(true) { //If zero count of the current window is less than m, wide the window to right. while(right < a.length && zeros <=m) { if(a[right] == 0) { if(zeros == m) {break;} zeros++; } right++; }
update the widest window if current window is more.
if(right-left>maxStreak) {
maxStreak = right-left;
maxL = left;
}
if(right == a.length) break;
//in order to find 0 in left, need to reduce 1 in left first. while(left < right && a[left] == 1) { left++; } if(left < a.length && a[left] == 0) { zeros--; left++; } } System.out.println("flipped 0 index:"); for(int i = maxL; i < maxL + maxStreak;i++) { if(a[i] == 0) { System.out.print(i); } } System.out.println(); return maxStreak; }
Comments
Post a Comment