
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
Find Index of 0 to Replace with 1 for Longest Sequence of 1s in Binary Array
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
Advertisements