- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- 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 zeroes to be flipped so that number of consecutive 1’s is maximized in C++
In this tutorial, we are going to find the zeroes count that need to be flipped to get maximum number of consecutive 1's in the array.
We are going to use the sliding window approach to solve the problem. Let's see the steps to solve the problem.
Initialize the array and max zeroes to be flipped.
Initialize window starting, ending indexes along with the length.
Store the max sub array of consecutive 1's length and starting index.
Iterate over the array until ending indexes crosses the array length.
If the zeroes count is less than the max zeroes count then increment the ending index and zeroes count if the current value is zero.
If the zeroes count is greater than the max zeroes count then increment the starting index and decrease zeroes count if the current value is zero.
Update the max window if the current window length is greater than the previous one.
Iterate over the array and print the zero indexes using window starting index.
Example
Let's see the code.
#include <bits/stdc++.h> using namespace std; void zeroesIndexes(int arr[], int maxZeroes, int n) { int start = 0, end = 0; int zeroesCount = 0; int bestWindowCount = 0, bestWindowStartIndex = 0; while (end < n) { if (zeroesCount <= maxZeroes) { if (arr[end] == 0) { zeroesCount++; } end++; } if (zeroesCount > maxZeroes) { if (arr[start] == 0) { zeroesCount--; } start++; } if ((end - start > bestWindowCount) && (zeroesCount <= maxZeroes)) { bestWindowCount = end - start; bestWindowStartIndex = start; } } cout << "The indexes are "; for (int i = 0; i < bestWindowCount; ++i) { if(arr[bestWindowStartIndex + i] == 0) cout << bestWindowStartIndex + i << " "; } } int main() { int arr[] = {1, 0, 0, 1, 1, 0, 1, 0, 1, 1}; int maxZeroes= 2; zeroesIndexes(arr, maxZeroes, 10); return 0; }
Output
If you run the above code, then you will get the following result.
The indexes are 5 7
Conclusion
If you have any queries in the tutorial, mention them in the comment section.