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 (containing and ).
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 .
As Alex is a newbie in his field, help him for the same, and output the required length of the sub array containing only .
Input Format:
First line consists of one integer , 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 .
Input Constraints:
Explanation
Here .
And if we choose positions and (1 based indexing in array), we can swap their values and the length of the sub-array (from index to ) containing only , will be .
Answer::
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
Post a Comment