Last active
August 19, 2017 02:42
-
-
Save ibreakthecloud/03bfed8d0e19280d19bb3d441d3d66e9 to your computer and use it in GitHub Desktop.
Swapping a digit and printing highest possible subset of 1's in a array containing 0's and 1's
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Author: Harshvardhan Karn | |
#include <stdio.h> | |
main() | |
{ | |
int a[100],n,i=0,counter=0,z=0,countfwd=0,countbwd=0,max=0,maxpos=0,countedtill=0, maxswap = 0, onecounter = 0; | |
//taking size of array | |
scanf("%d",&n); | |
//taking input for array | |
for(i=0;i<n;i++) | |
{ | |
scanf("%d",&a[i]); | |
} | |
//searching for sub array | |
while(counter<n) //run till array ends | |
{ | |
if (a[counter] == 0 ) //when zero encounters take it as a point and then | |
{ //Forwards | |
if(counter < n && a[counter+1] == 1) // run forward if next to it is 1 | |
{ | |
z=counter+1; //forward 1th position stored in z | |
while(a[z] == 1 && z <= n) | |
{ | |
countfwd++; | |
z++; //z is current position | |
} | |
if(countfwd > max ) | |
{ | |
max = countfwd; | |
maxpos = z; | |
//countfwd = 0; | |
countedtill = z; | |
} | |
} | |
//backwards | |
if(a[counter-1] == 1 && counter > 0) // run backwards if next to it is 1 | |
{ | |
z=counter-1; //backwards 1th position stored in z | |
while(a[z] == 1 && z >= 0 ) | |
{ | |
countbwd++; | |
z--; //z is current position | |
} | |
if(countbwd > max ) | |
{ | |
max = countbwd; | |
maxpos = counter; | |
countedtill = z; | |
//countbwd = 0; | |
} | |
} | |
if(a[counter+1] == a[counter-1]) | |
{ | |
if(max<(countfwd+countbwd)) | |
{ | |
max = countfwd+countbwd; | |
} | |
} | |
countfwd = countbwd = 0; | |
} | |
else //it will execute when there are only 1 in array | |
{ | |
onecounter++; | |
} | |
counter++; | |
} | |
if(max == 0) | |
{ | |
if(onecounter == n) | |
{ | |
maxswap = n; | |
} | |
else | |
{ | |
maxswap= max; | |
} | |
} | |
else if(max == onecounter) //if there is no remaining 1 other than the found in subset, to swap | |
{ | |
maxswap = max; | |
} | |
else | |
{ | |
maxswap = max + 1; // +1 because swapping will done here after | |
} | |
printf("%d ", maxswap); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment