
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
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 Articles
- 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++
- 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 by rearranging bits in C++
- Maximize the number of sum pairs which are divisible by K in C++
- Maximize a given unsigned number by swapping bits at its extreme positions in C++
- Encoding a number string into a string of 0s and 1s in JavaScript
- Maximize the product of four factors of a Number in C++
- Program to count number of switches that will be on after flipping by n persons in python
- Maximize the maximum subarray sum after removing at most one element 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++
- C++ Program to Generate a Random Subset by Coin Flipping
- Find the Number of Primes In A Subarray using C++

Advertisements