

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
Find Index of 0 to be replaced with 1 to get longest continuous sequence of 1s in a binary array in C++
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
#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); }
Output
Index of 0 to be replaced is 9
- 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
- Program to find length of longest substring with 1s in a binary string after one 0-flip 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 1s in binary form of n in Python
- Program to find length longest prefix sequence of a word array in Python
- Find the index of first 1 in an infinite sorted array of 0s and 1s in C++
- Program to find longest consecutive run of 1 in binary form of a number in C++
- Find the index of first 1 in a sorted array of 0's and 1's in C++
- Longest distance between 1s in binary JavaScript
- Program to find length of longest consecutive sequence in Python
- 1 to n bit numbers with no consecutive 1s in binary representation?
- Binary Tree Longest Consecutive Sequence in C++
- Find perimeter of shapes formed with 1s in binary matrix in C++
Advertisements