Minimum flip in an Binary Array GFG
public class MinimumFlip {
// Efficient solution
public static void printFlips(int[] arr) {
int n = arr.length;
for(int i = 1; i < n; i++) {
if(arr[i] != arr[i - 1]) {
if(arr[i] != arr[0]) {
System.out.print("From " + i + " to ");
}
else
System.out.println(i - 1);
}
}
if(arr[n - 1] != arr[0]){
System.out.println(n - 1);
}
}
// Minimum flip
public static void getMinFlip(int[] arr) {
int n = arr. length;
int count_One = 0;
int count_Zero = 0;
for( int i = 1; i < n; i++) {
if(arr[i - 1] == 1 && arr[i] == 0) {
count_One++;
break;
// System.out.println(count_One);
}
else if(arr[i - 1] == 0 && arr[i] == 1){
count_Zero++;
break;
// System.out.println(count_Zero);
}
}
int index = 0 ;
if(count_One == 1){
for(int i = 0; i < n; i += index) {
for(int j = i + 1; j < n; j++) {
if(arr[i] == 0 && (arr[j] == 1 || j == n - 1)){
System.out.println("From " + i + " to " + (j - 1));
index = j;
}
}
}
}
else{
int index1 = 0;
for(int i = 0; i < n; i += index1) {
for(int j = i + 1; j < n; j++) {
if(arr[i] == 1 && (arr[j] == 0 || j == n - 1)){
System.out.println("From " + i + " to " + (j - 1));
index1 = j;
}
}
}
}
}
public static void main(String[] args) {
int[] array = {1,1,0,0,0,1,0};
printFlips(array);
}
}
Comments
Post a Comment