Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * Problem 2: Bit Flip
- *
- * Given an array of binary values (0 and 1) and N number of flips (convert
- * a 0 to a 1), determine the maximum number of consecutive 1's that can be
- * made.
- *
- * Input: An Array of 1's and 0's, and an Integer N denoting the number of
- * flips
- * Output: Integer
- *
- * Example: bitFlip([0,1,1,1,0,1,0,1,0,0], 2)
- * Result: 7
- */
- // Time Complexity:
- // Auxiliary Space Complexity:
- import java.io.*;
- import java.util.*;
- class Problems {
- public static void main(String[] args){
- int[] arr = {0,1,1,1,0,1,0,1,0,0};
- int n = 5;
- System.out.println(BitFlip(arr, n));
- }
- public static int BitFlip(int[] arr, int N) {
- int numZeros = 0;
- int len = arr.length;
- for(int i = 0; i< len; i++){
- if(arr[i] == 0){
- numZeros++;
- }
- }
- if(N == numZeros){
- return len;
- }
- //if the array has only 1 zero and there are no flips--> return 0
- if(len == 1 && N == 0){
- return 0;
- }
- int numFlips = N;
- int index = 0;
- while(numFlips > -1 ){
- //if the element is 0 -> flip it and decrement numFlips
- if(arr[index] == 0){
- numFlips--;
- index++;
- }else if(arr[index] == 1){
- index++;
- }
- }
- return index;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement