
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
Minimum Operations Required to Remove an Array in C++
Description
Given an array of N integers where N is an even number. There are two kinds of operations allowed on the array.
- Increase the value of any element of an array by 1.
- If two adjacent elements in the array are consecutive prime number, delete both the element.
The task is to find the minimum number of operations required to remove all the element of the array.
Example
If array is {10, 13} then minimum 2 operations are required
- Increment 1st element of an array by 1. So new array becomes {11, 13}
- Delete 1st and 2nd element as both are consecutive prime numbers
Algorithm
1. To remove numbers, we must transform two numbers to two consecutive primes. 2. Let us suppose a and b are the consecutive prime numbers then we use sieve of Eratosthenes to precompute prime numbers and then find the first prime p not greater than a and the first greater than p using array 3. Once this computation is done use dynamic programming to solve the problem
Example
#include <iostream> #include <algorithm> #include <queue> using namespace std; int minimumPrefixReversals(int *a, int n) { string start = ""; string destination = "", t, r; for (int i = 0; i < n; i++) { start += to_string(a[i]); } sort(a, a + n); for (int i = 0; i < n; i++) { destination += to_string(a[i]); } queue<pair<string, int> > qu; pair<string, int> p; qu.push(make_pair(start, 0)); if (start == destination) { return 0; } while (!qu.empty()) { p = qu.front(); t = p.first; qu.pop(); for (int j = 2; j <= n; j++) { r = t; reverse(r.begin(), r.begin() + j); if (r == destination) { return p.second + 1; } qu.push(make_pair(r, p.second + 1)); } } } int main() { int a[] = { 1, 2, 4, 3 }; int n = sizeof(a) / sizeof(a[0]); cout << "Minimum reversal: " << minimumPrefixReversals(a, n) << endl; return 0; }
When you compile and execute above program. It generates following output:
Output
Minimum reversal: 3
Advertisements