
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 −
#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