Max Consecutive Ones II in C++


Suppose we have a binary array; we have to find the maximum number of consecutive 1s in this array if we can flip at most one 0.

So, if the input is like [1,0,1,1,0], then the output will be 4 because if we flip the first zero will get the maximum number of consecutive 1s. After flipping, the maximum number of consecutive 1s is 4.

To solve this, we will follow these steps −

  • ret := 1, n := size of nums

  • if not n is non-zero, then −

    • return 0

  • j := 0, zero := 0

  • for initialize i := 0, when i < n, update (increase i by 1), do −

    • if nums[i] is same as 0, then −

      • (increase zero by 1)

    • while (j <= i and zero > 1), do −

      • if nums[j] is same as 0, then −

        • (decrease zero by 1)

      • (increase j by 1)

    • ret := maximum of ret and (i - j + 1)

  • return ret

Example 

Let us see the following implementation to get better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
   int findMaxConsecutiveOnes(vector<int<& nums) {
      int ret = 1;
      int n = nums.size();
      if (!n)
         return 0;
      int j = 0;
      int zero = 0;
      for (int i = 0; i < n; i++) {
         if (nums[i] == 0) {
            zero++;
         }
         while (j <= i && zero > 1) {
            if (nums[j] == 0) {
               zero--;
            }
            j++;
         }
         ret = max(ret, i - j + 1);
      }
      return ret;
   }
};
main(){
   Solution ob;
   vector<int< v = {1,0,1,1,1,0,1,1};
   cout << (ob.findMaxConsecutiveOnes(v));
}

Input

{1,0,1,1,1,0,1,1}

Output

6

Updated on: 19-Nov-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements