
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
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
- Related Articles
- Max Consecutive Ones III in C++
- Consecutive ones with a twist in JavaScript
- Non-negative Integers without Consecutive Ones in C++
- Program to find minimum adjacent swaps for K consecutive ones in Python
- Moving Stones Until Consecutive II in C++
- Max Chunks To Make Sorted II in C++
- Binary Tree Longest Consecutive Sequence II in C++
- Ones and Zeroes in C++
- Maximum Number of Ones in C++
- Deletion of Max Element from a Max HBLT In Data Structure
- max() function in PHP
- Max Heap in Java
- Count Square Submatrices with All Ones in C++
- LongStream max() method in Java
- DoubleStream max() method in Java
