C++ code to count colors to paint elements in valid way

Suppose we have an array A with n elements. We need to paint elements in colors such that −

  • If we consider any color, all elements of this color must be divisible by the minimal element of the same color.

  • The number of used colors should be minimized.

We have to find the minimum number of colors to paint all the given numbers in a valid way.

So, if the input is like A = [10, 2, 3, 5, 4, 2], then the output will be 3, because paint the first color to the elements A[0] and A[3], paint second color to the elements A[2] and paint the third color to the remaining three elements.

Steps

To solve this, we will follow these steps −

n := size of A
ans := 0
sort the array A
for initialize i := 0, when i 

Example

Let us see the following implementation to get better understanding −

#include 
using namespace std;
int solve(vector A){
   int n = A.size();
   int ans = 0;
   sort(A.begin(), A.end());
   for (int i = 0; i  A = { 10, 2, 3, 5, 4, 2 };
   cout 

Input

{ 10, 2, 3, 5, 4, 2 }

Output

3
Updated on: 2022-03-29T09:08:13+05:30

348 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements