# Minimum number of operations required to delete all elements of the array using C++.

C++Server Side ProgrammingProgramming

## Problem statement

Given an integer array arr, the task is to print the minimum number of operations required to delete all elements of the array. While deleting element following restriction is imposed −

• Any element from the array can be chosen at random and every element divisible by it can be removed from the array

If arr[] = {2, 4, 15, 10, 8, 5, 3} then 3 operation are required to delete all elements −

• If we choose 2 then it will delete {2, 4, 10, 8}
• If we choose 5 then it will remove {5, 15}
• If we choose 3 then it will remove {3}

## Algorithm

1. Sort the array in ascending order and count number occurrence of each element
2. For each unmarked element starting from beginning mark all elements which are divisible by choose element, and increase the result counter

## Example

#include <iostream>
#include <algorithm>
#define SIZE(arr) (sizeof(arr) / sizeof(arr[0]))
#define MAX 100
using namespace std;
int getMinOperations(int *arr, int n){
int map[MAX] = {0};
sort(arr, arr + n);
for (int i = 0; i < n; ++i) {
map[arr[i]]++;
}
int cnt = 0;
for (int i = 0; i < n; ++i) {
if (map[arr[i]]) {
for (int j = i; j < n; ++j) {
if (arr[j] % arr[i] == 0) {
map[arr[j]] = 0;
}
}
++cnt;
}
}
return cnt;
}
int main(){
int arr[] = {2, 4, 15, 10, 8, 5, 3};
cout << "Minimum required operations = " << getMinOperations(arr, SIZE(arr)) << endl;
return 0;
}

## Output

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

Minimum required operations = 3
Published on 31-Oct-2019 07:21:16