- Related Questions & Answers
- XOR counts of 0s and 1s in binary representation in C++
- Print n 0s and m 1s such that no two 0s and no three 1s are together in C Program
- Minimum flips to make all 1s in left and 0s in right in C++
- Count all 0s which are blocked by 1s in binary matrix in C++
- Minimum flips in two binary arrays so that their XOR is equal to another array in C++.
- Check if a binary string has a 0 between 1s or not in C++
- Add minimum number to an array so that the sum becomes even in C++?
- Find the minimum value to be added so that array becomes balanced in C++
- Find minimum value to assign all array elements so that array product becomes greater in C++
- Add minimum number to an array so that the sum becomes even in C programming
- Segregate all 0s on right and 1s on left in JavaScript
- Convert given string so that it holds only distinct characters in C++
- Ways to remove one element from a binary string so that XOR becomes zero in C++
- Appending data to a MySQL field that already has data in it?
- Maximum number of edges to be added to a tree so that it stays a Bipartite graph in C++

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

Given an array of n integers containing only 0 and 1. Find the minimum toggles (switch from 0 to 1 or vice-versa) required such the array the array become partitioned, i.e., it has first 0s then 1s.

If arr[] = {1, 0, 0, 1, 1, 1, 0} then 2 toggle is required i.e. toggle first one and last zero.

- If we observe the question, then we will find that there will definitely exist a point from 0 to n-1 where all elements left to that point should contains all 0’s and right to point should contains all 1’s
- Those indices which don’t obey this law will have to be removed. The idea is to count all 0s from left to right.

#include <bits/stdc++.h> using namespace std; int getMinToggles(int *arr, int n) { int zeroCnt[n + 1] = {0}; for (int i = 1; i <= n; ++i) { if (arr[i - 1] == 0) { zeroCnt[i] = zeroCnt[i - 1] + 1; } else { zeroCnt[i] = zeroCnt[i - 1]; } } int result = n; for (int i = 1; i <= n; ++i) { result = min(result, i - zeroCnt[i] + zeroCnt[n] - zeroCnt[i]); } return result; } int main() { int arr[] = {1, 0, 0, 1, 1, 1, 0}; int n = sizeof(arr) / sizeof(arr[0]); cout << "Minimum toggles = " << getMinToggles(arr, n) << endl; return 0; }

When you compile and execute above program. It generates following output −

Minimum toggles = 2

Advertisements