Find Zeros to be Flipped so that number of Consecutive 1’s is maximized in C

Find Zeros to be Flipped so that number of Consecutive 1’s is maximized in C

 

In this page we will look into a coding question where we will learn how to find the zeros that needs to be flipped so that the number of consecutive 1’s is maximized
There might be different approach to solve this question, one you will find here. If your approach is bit different post it onto the comment section.

Find Zeros to be Flipped so that number of Consecutive 1’s is maximized in C

Find Zeros to be Flipped so that number of Consecutive 1’s is maximized in C

Here are the step-by-step instructions to solve this problem:

  1. Initialize two pointers left and right to the beginning of the array.
  2. Initialize a variable zero_count to keep track of the number of zeroes seen so far and another variable max_ones to keep track of the maximum number of consecutive ones seen so far.
  3. Move the right pointer to the right until we reach a zero. At this point, increment zero_count.
  4. If zero_count is greater than m, move the left pointer to the right until we have flipped the required number of zeroes (i.e., zero_count – m). Update zero_count accordingly.
  5. Update max_ones to be the maximum of its current value and the length of the current sequence of ones (i.e., right – left + 1).
  6. Repeat steps 3-5 until the end of the array is reached.
  7. Return max_ones.
The above steps use a sliding window approach to keep track of the current sequence of ones and the number of zeroes seen so far. The left pointer is used to keep track of the start of the current sequence of ones, while the right pointer is used to move through the array. The zero_count variable is used to keep track of the number of zeroes seen so far, while max_ones is used to keep track of the maximum number of consecutive ones seen so far.
Find Zeros to be Flipped so that number of Consecutive 1’s is maximized in C

Program to find zeros to be flipped so that binary number is maximized in C

Run
#include <stdio.h>

int max (int a, int b)
{
  return a > b ? a : b;
}

int find_zeroes_to_flip (int arr[], int n, int zeros)
{
  int left = 0, right = 0, zero_count = 0, max_ones = 0;
  while (right < n)
    {
      if (arr[right] == 0)
	{
	  zero_count++;
	}
      while (zero_count > zeros)
	{
	  if (arr[left] == 0)
	    {
	      zero_count--;
	    }
	  left++;
	}
      max_ones = max (max_ones, right - left + 1);
      right++;
    }
  return max_ones;
}

int main ()
{
  int arr[] = { 1, 0, 1, 0, 1, 1, 0, 1, 1, 1 };
  int n = sizeof (arr) / sizeof (arr[0]);
  int zeros = 1;
  int max_consecutive_ones = find_zeroes_to_flip (arr, n, zeros);
  printf ("Max consecutive ones after flipping %d zeroes: %d\n", zeros,
	  max_consecutive_ones);
  return 0;
}

Output:

Max consecutive ones after flipping 1 zeroes: 6