Flip Bits | Practice | GeeksforGeeks

Given an array A[] consisting of 0’s and 1’s. A flip operation is one in which you turn 1 into 0 and a 0 into 1. You have to do at most one “Flip” operation of any subarray. Formally, select a range (l, r) in the array A[], such that (0 ≤ l ≤ r < n) holds and flip the elements in this range to get the maximum ones in the final array. You can possibly make zero operations to get the answer.
 
Example 1:
Input:
N = 5
A[] = {1, 0, 0, 1, 0} 
Output:
4
Explanation:
We can perform a flip operation in the range [1,2]
After flip operation array is : [ 1 1 1 1 0 ]
Count of one after fliping is : 4
[Note: the subarray marked in bold is the flipped subarray]
 
Example 2:
Input:
N = 7
A[] = {1, 0, 0, 1, 0, 0, 1}
Output:
6
Explanation:
We can perform a flip operation in the range [1,5]
After flip operation array is : [ 1 1 1 0 1 1 1]
Count of one after fliping is : 6
[Note: the subarray marked in bold is the flipped subarray]
 
Your Task:  
You don't need to read input or print anything. Your task is to complete the function maxOnes() which takes the array A[] and its size N as inputs and returns the maximum number of 1's you can have in the array after atmost one flip operation.
 
Expected Time Complexity: O(N)
Expected Auxiliary Space: O(1)
 
Constraints:
1 ≤ N ≤ 104
0 ≤ A[i] ≤ 1
+1
srisai_pasupuleti1 week ago
here is concise  O(n) java solution
public static int maxOnes(int a[], int n) {
        int[] h=new int[2];
        h[0]=1;h[1]=-1;
        int sum=0,maxsum=0,total=0;
        for(int i=0;i<n;i++){
            total+=a[i];
            sum+=h[a[i]];
            if(sum>maxsum){
                maxsum=sum;
            }
            if(sum<0){sum=0;}
        }
        return total+maxsum;
    }
-1
jimmy981602 months ago
public:   int maxOnes(int a[], int n)   {       int sum=0, maxsum=0, total=0;       // Your code goes here       for (int i=0; i<n; i++){           int curr = a[i];           total += a[i];           if (curr == 0){               curr=1;           }           else{               curr=-1;           }           sum += curr;           sum = max(curr, sum);           maxsum = max(sum, maxsum);       }       return (total+maxsum);   }
0
shivanshpandey1573 months ago
 int ans=INT_MAX,count=0,sum=0;       for(int i=0;i<n;i++)       {           if(a[i]==0)           a[i]=-1;           else           count++;       }       for(int i=0;i<n;i++)       {           if(sum+a[i]<0)           {               sum+=a[i];               ans=min(ans,sum);           }           else           {               sum=0;           }       }       if(ans==INT_MAX)       return count;       return count+abs(ans);
0
sriharichalla1220024 months ago
def maxOnes(self, a, n):       # Your code goes here       ones = 0       sum = 0        max_sum = 0       for i in range(n):                  if a[i] == 1:               ones+=1           value = -1 if a[i] == 1 else 1           sum = sum+value           max_sum = max(sum,max_sum)           if sum < 0:               sum = 0       return max_sum+ones
+2
arun1331prasad4 months ago
class Solution {
    public static int maxOnes(int a[], int n) {
        int totalones=0;
        int currsum=0;
        int maxsum=0;
     for( int i=0; i<n;i++){
         if(a[i]==1)
         totalones++;
         int val= a[i]==1?-1:1;
         currsum+=val;
         if(currsum>maxsum){
             maxsum=currsum;
         }
         if(currsum<0){
             currsum=0;
         }
     }
     return totalones+maxsum;
    }
}

0
ashutoshchoudhary9984 months ago
class Solution {
   public static int maxOnes(int a[], int n) {       // Your code goes here       int current=0;       int ones=0;       int max=0;       for(int i=0;i<n;i++){           if(a[i]==1){               ones++;           }                      int val=0;           val=(a[i]==1)?-1:1;                      current=Math.max(current+val,val);           max=Math.max(max,current);                           }              return max+ones;   }} 
+3
ameenul88089 months ago
int maxOnes(int a[], int n)
    {
        // Your code goes here
        //uisng kadane's
        int msf=0,meh=0;
        for(int i=0;i<n;i++){
            meh += (a[i])?-1:1;
    
            if(meh>msf){
                msf=meh;
            }
            
            if(meh<0){
                meh=0;
            }
        }
        
        for(int i=0;i<n;i++){
            if(a[i]) msf++;
        }
        
        return msf;
    }
0
b181399 months ago
#include<bits/stdc++.h>
using namespace std;
 
 // } Driver Code Ends
 
 
class Solution{
    public:
    int maxOnes(int a[], int n)
    {
        int zc=0 , oc=0;
        for(int i=0;i<n;i++)
        {
            if(a[i]==1) oc++;
        }
        if(oc==n or oc==n-1) return n;
        int flip=0;
        int curr=0;
        int i=0;
        while(a[i]==1) i++;
        for(i;i<n;i++)
        {
            if(a[i]==1) curr--;
            else if(a[i]==0) curr++;
            flip=max(flip, curr);
        }
        return flip+oc;
    }
};
 
 
// { Driver Code Starts.
int main()
{
    int t; cin>>t;
    while(t--)
    {
        int n;
        cin>>n;
        int a[n+5];
        for(int i=0;i<n;i++)
            cin>>a[i];
        Solution ob;
        cout<< ob.maxOnes(a, n) <<endl;
    }
    return 0;
}
  // } Driver Code Ends
 
 
// CAN ANYONE PLEASE TELL ME WHAT'S WRONG WITH MY APPROACH HERE
0
Abdullah Jamal1 year ago int maxOnes(int bits[], int n)    {        int zeroesCount = 0, maxZeroes = 0;         // count zeroes in the range where (num of zeroes > num of ones)        // and find their max        for(int i = 0; i < n; i++){            if(bits[ i ] == 0)                 zeroesCount ++;            else                 zeroesCount --;            if(zeroesCount < 0)                zeroesCount = 0;             maxZeroes = max(maxZeroes, zeroesCount);        }         // add ones in array to maxZeroes        for(int i = 0; i < n; i++){            if(bits[ i ])                maxZeroes++;        }         return maxZeroes;    }Reply Open ExternallyShow 0 RepliesLoading...
Abdullah Jamal
 int maxOnes(int bits[], int n)    {        int zeroesCount = 0, maxZeroes = 0;         // count zeroes in the range where (num of zeroes > num of ones)        // and find their max        for(int i = 0; i < n; i++){            if(bits[ i ] == 0)                 zeroesCount ++;            else                 zeroesCount --;            if(zeroesCount < 0)                zeroesCount = 0;             maxZeroes = max(maxZeroes, zeroesCount);        }         // add ones in array to maxZeroes        for(int i = 0; i < n; i++){            if(bits[ i ])                maxZeroes++;        }         return maxZeroes;    }
0
Siddharth Singh2 years agoSimply, here we have to use Kadane's Algorithm (Maximum Sum Subarray):#include<bits stdc++.h="">using namespace std;int main() {int t;cin>>t;while(t--){    int n;    cin>>n;    vector<int>v(n);    for(int &i : v) cin>>i;    int noOfZeros=0;    int noOfOnes=0;    int maxZeroes = 0;     for(int i=0; i<n; i++){="" if(v[i]="=0){" noofzeros++;="" }else{="" noofones++;="" noofzeros--;="" }="" maxzeroes="max(maxZeroes," noofzeros);="" noofzeros="max(0,noOfZeros);" }="" int="" res="noOfOnes" +="" maxzeroes;="" cout<<res<<"\n";="" }="" return="" 0;="" }="" <="" code="">Reply Open ExternallyShow 1 RepliesLoading...
Siddharth Singh
Simply, here we have to use Kadane's Algorithm (Maximum Sum Subarray):
#include<bits stdc++.h="">using namespace std;int main() {int t;cin>>t;while(t--){    int n;    cin>>n;    vector<int>v(n);    for(int &i : v) cin>>i;    int noOfZeros=0;    int noOfOnes=0;    int maxZeroes = 0;     for(int i=0; i<n; i++){="" if(v[i]="=0){" noofzeros++;="" }else{="" noofones++;="" noofzeros--;="" }="" maxzeroes="max(maxZeroes," noofzeros);="" noofzeros="max(0,noOfZeros);" }="" int="" res="noOfOnes" +="" maxzeroes;="" cout<<res<<"\n";="" }="" return="" 0;="" }="" <="" code="">
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested 
                                    against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code.
                                    On submission, your code is tested against multiple test cases consisting of all
                                        possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as
                                        the final solution code.
You can view the solutions submitted by other users from the submission tab.
Make sure you are not using ad-blockers.
Disable browser extensions.
We recommend using latest version of your browser for best experience.
Avoid using static/global variables in coding problems as your code is tested 
                                against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases in coding problems does not guarantee the 
                                correctness of code. On submission, your code is tested against multiple test cases
                                    consisting of all possible corner cases and stress constraints.