
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 Minimum Operations to Make an Array Beautiful in C++
In this problem, we are given a binary array bin[] consisting n binary values which happen to be 0 and 1. Our task is to find minimum operations needed to make an Array beautiful.
Beautiful array is a special type of binary array which consists of a pattern of alternate 0’s and 1’s.
Problem Description − We need to find the number operations that are required to make the array beautiful. An operations consists of these steps −
Step 1 − Cut the array into two halves.
Step 2 − Reverse any one of the two halves.
Step 3 − Join then halves back.
We will be counting the number of operations that are required to make sure that the array becomes a beautiful array.
Let’s take an example to understand the problem,
Input
bin[] = {1, 0, 1, 0, 0, 1}
Output
1
Explanation
We will cut the array, make a subarray bin[4, 5], reverse it and join it back.
Solution Approach
The solution to the problem is based on finding the minimum number of switch operations which is equal to the number of consecutive zeros. The base cases are −
If the size of the array is 1, it is a beautiful array. If the size of the array is an odd number then it can never be a beautiful array.
For all even lengths, we will check the total number of consecutive zeros or ones which will be the number of operations to be performed.
Algorithm
Initialise − zeroCount , oneCount, consZero = 0
Step 1 − if ( n = 1), return 0
Step 2 − if (n%2 != 0), return -1.
Step 3 − Loop for i -> 0 to n-1.
Step 3.1 − if bin[i] == bin[i+1] == 0, consZero++.
Step 4 − if bin[n-1] == bin[0] == 0, consZero++.
Step 5 − return consZero.
Program to illustrate the working of our solution,
Example
#include <iostream> using namespace std; int minOperations(int bin[], int n) { if(n == 1) return 0; if(n%2 != 0) return -1; int consZero = 0; for (int i = 0; i < n; ++i) { if (i + 1 < n) { if (bin[i] == 0 && bin[i + 1] == 0) consZero++; } } if (bin[0] == bin[n - 1] && bin[0] == 0) consZero++; return consZero; } int main() { int bin[] = { 1, 0, 1, 0, 0, 1}; int n = sizeof(bin) / sizeof(bin[0]); cout<<"The minimum operations needed to make an Array beautiful is "<<minOperations(bin, n); return 0; }
Output
The minimum operations needed to make an Array beautiful is 1