

- 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
Maximize number of 0s by flipping a subarray in C++
Problem statement
Given a binary array, find the maximum number of zeros in an array with one flip of a subarray allowed. A flip operation switches all 0s to 1s and 1s to 0s
If arr1= {1, 1, 0, 0, 0, 0, 0}
If we flip first 2 1’s to 0’s, then we can get subarray of size 7 as follows −
{0, 0, 0, 0, 0, 0, 0}
Algorithm
1. Consider all subarrays and find a subarray with maximum value of (count of 1s) – (count of 0s) 2. Considers this value be maxDiff. Finally return count of zeros in original array + maxDiff.
Example
#include <bits/stdc++.h> using namespace std; int getMaxSubArray(int *arr, int n){ int maxDiff = 0; int zeroCnt = 0; for (int i = 0; i < n; ++i) { if (arr[i] == 0) { ++zeroCnt; } int cnt0 = 0; int cnt1 = 0; for (int j = i; j < n; ++j) { if (arr[j] == 1) { ++cnt1; } else { ++cnt0; } maxDiff = max(maxDiff, cnt1 - cnt0); } } return zeroCnt + maxDiff; } int main(){ int arr[] = {1, 1, 0, 0, 0, 0, 0}; int n = sizeof(arr) / sizeof(arr[0]); cout << "Maximum subarray size = " << getMaxSubArray(arr, n) << endl; return 0; }
Output
When you compile and execute the above program. It generates the following output−
Maximum subarray size = 7
- Related Questions & Answers
- Largest subarray with equal number of 0s and 1s in C++
- Maximum subarray sum by flipping signs of at most K array elements in C++
- Maximize the number by rearranging bits in C++
- Reverse Subarray To Maximize Array Value in C++
- Maximize the subarray sum after multiplying all elements of any subarray with X in C++
- Maximize the number of sum pairs which are divisible by K in C++
- Maximize the product of four factors of a Number in C++
- C++ Program to Generate a Random Subset by Coin Flipping
- Encoding a number string into a string of 0s and 1s in JavaScript
- Program to count number of switches that will be on after flipping by n persons in python
- Maximize a given unsigned number by swapping bits at its extreme positions in C++
- Maximize number of continuous Automorphic numbers in C++
- Maximize the given number by replacing a segment of digits with the alternate digits given in C++
- Find the Number of Primes In A Subarray using C++
- Program to maximize number of nice divisors in Python
Advertisements