- Related Questions & Answers
- Find Indexs of 0 to be replaced with 1 to get longest continuous sequence of 1s in a binary array - Set-2 in C++
- Find Indexs of 0 to be replaced with 1 to get longest continuous sequence of 1s in a binary array - Set-2 in Python
- Find longest sequence of 1’s in binary representation with one flip in C++
- Program to find longest distance of 1s in binary form of a number using Python
- Program to find longest consecutive run of 1 in binary form of a number in C++
- Binary Tree Longest Consecutive Sequence in C++
- Find perimeter of shapes formed with 1s in binary matrix in C++
- C++ Program to Find the Longest Increasing Subsequence of a Given Sequence
- C++ Program to Find the Longest Prefix Matching of a Given Sequence
- Longest distance between 1s in binary JavaScript
- Program to find length of longest consecutive sequence in Python
- Binary Tree Longest Consecutive Sequence II in C++
- Find duplicates in constant array with elements 0 to N-1 in O(1) space in C++
- C# program to find the length of the Longest Consecutive 1’s in Binary Representation of a given integer
- Find if there is any subset of size K with 0 sum in an array of -1 and +1 in C++

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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.

#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[0]); cout << "Index of 0 to be replaced is "<< findIndex(arr, n); }

Index of 0 to be replaced is 9

Advertisements