Commonly asked Data Structures and Algorithms Problems by big tech and different solution approaches with code in Java and C

Powered by Blogger.

Tuesday, March 20, 2018

Maximize no of 1 by flipping k 0


Idea is to sliding window concept.
For first k 0's increase right window index.

When we already have gone through k 0's then increase left window index to first occurrence of 0 from leftwindow index.


     public static int max1(int arr[],int n,int k)
     {
         int i=0;
         int max=0;
         int startindex=0;
         while(i<n)
         {
             if(arr[i]==0){
//decrement count of bits that can be changed
             if(k>0)
             {
                 --k;
             }
else
{
while(startindex<=i && arr[startindex++]!=0);
 
}
}
++i;
max=Math.max(max,i-startindex);
         }
return max;
}


Another approach with same concept
https://www.careercup.com/question?id=5106425965576192
}

0 Comments:

Post a Comment

Stats