Hackers with Bits - A question I saw

Hackers love bits, so does Alex. Alex has just started his career as hacker and found a special binary array A (containing 0s and 1s).
In one operation, he can choose any two positions in the array, and can swap their values. He has to perform exactly one operation and maximize the length of the subarray containing only 1s.
As Alex is a newbie in his field, help him for the same, and output the required length of the sub array containing only 1s.

Input Format:
First line consists of one integer N, denoting the number of elements in the array.
Second line consists of N space-separated integers, denoting the elements of the array.
Output Format:
Print the required length of the sub array containing only 1s.
Input Constraints:



1N100


SAMPLE INPUT
 
5
1 1 1 0 1
SAMPLE OUTPUT
 
4
Explanation
Here N=5.
And if we choose positions 4th and 5th (1 based indexing in array), we can swap their values and the length of the sub-array (from index 1 to 4) containing only 1s, will be 4.




Answer::

#include <stdio.h>

int main()
{
    int n,i;
    int max_count = 0; 
    int count=0;// for maximum number of 1 around a zero
    int max_index=0; // for storing result
    int prev_zero = -1; // index of previous zero
    int prev_prev_zero = -1; // index of previous to previous zero

    int arr[100];
    scanf("%d",&n);
    for(i=0;i<n;i++)
        scanf("%d",&arr[i]);
    // Traverse the input array
    for (int curr=0; curr<n; ++curr)
    {
        // If current element is 0, then calculate the difference
        // between curr and prev_prev_zero
        if (arr[curr] == 0)
        {
            // Update result if count of 1s around prev_zero is more
            if (curr - prev_prev_zero > max_count)
            {
                max_count = curr - prev_prev_zero;
                max_index = prev_zero;
            }

            // Update for next iteration
            prev_prev_zero = prev_zero;
            prev_zero = curr;
        }
    }

    // Check for the last encountered zero
    if (n-prev_prev_zero > max_count)
        max_index = prev_zero;

        for(i=0;i<n;i++)
         {
             if(i==max_index)
             {
                int temp=arr[i];
               arr[i]=arr[i+1];
              arr[i+1]=temp;
            }

        }
 for(int i=0;i<n;i++)
    {
        if(arr[i]==1)
        count++;
    }


    printf("%d",count);
    return 0;
}






Comments

Popular posts from this blog

Complementary Color

How to extract tweets from python.