# Find Index of 0 to be replaced with 1 to get longest continuous sequence of 1s in a binary array in C++

C++Server Side ProgrammingProgramming

Suppose, we have an array of N elements. These elements are either 0 or 1. Find the position of 0 to be replaced with 1 to get longest contiguous sequence of 1s. Suppose the array is like arr = [1, 1, 0, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1], the output index is 9. Replacing 0 with 1 at index 9 cause the maximum contiguous sequence of 1s

We have to keep track of three indexes. current index(curr), previous zero index(pz), and previous to previous zero index (ppz). Now traverse the array when array element is 0, then calculate difference between curr and ppz, If the difference is more than max, then update the maximum, finally return index of the prev_zero with max difference.

## Example

Live Demo

#include<iostream>
using namespace std;
int findIndex(bool arr[], int n) {
int count_max = 0;
int index;
int pz = -1;
int ppz = -1;
for (int curr=0; curr<n; curr++) {
if (arr[curr] == 0) {
if (curr - ppz > count_max){
count_max = curr - ppz;
index = pz;
}
ppz = pz;
pz = curr;
}
}
if (n-ppz > count_max)
index = pz;
return index;
}
int main() {
bool arr[] = {1, 1, 0, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1};
int n = sizeof(arr)/sizeof(arr);
cout << "Index of 0 to be replaced is "<< findIndex(arr, n);
}

## Output

Index of 0 to be replaced is 9
Advertisements