- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- 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

# 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 < n, update (increase i by 1), do: ok := 1 for initialize j := 0, when j < i, update (increase j by 1), do: ok := ok AND (1 if A[i] mod A[j] is not 0, otherwise 0) ans := ans + ok return ans

## Example

Let us see the following implementation to get better understanding −

#include <bits/stdc++.h> using namespace std; int solve(vector<int> A){ int n = A.size(); int ans = 0; sort(A.begin(), A.end()); for (int i = 0; i < n; i++){ int ok = 1; for (int j = 0; j < i; j++) ok &= (A[i] % A[j] != 0); ans += ok; } return ans; } int main(){ vector<int> A = { 10, 2, 3, 5, 4, 2 }; cout << solve(A) << endl; }

## Input

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

## Output

3

- Related Questions & Answers
- C++ code to check pile count is valid from second day
- Program to find minimum cost to paint fences with k different colors in Python
- How to count the valid elements from a series object in Pandas?
- Ways to paint stairs with two colors such that two adjacent are not yellow in C++
- Ways to paint N paintings such that adjacent paintings don’t have same colors in C++
- Check for Valid hex code - JavaScript
- C++ Program to count operations to make filename valid
- Ways to paint N paintings such that adjacent paintings don’t have same colors in C programming
- Program to count number of valid triangle triplets in C++
- C++ code to count numbers after division elements greater than half of array size
- C++ program to count in how many ways we can paint blocks with two conditions
- The best way to hide a string in binary code in C++?
- C++ code to count days to complete reading book
- C++ code to count ways to form reconnaissance units
- C++ code to count operations to make array sorted

Advertisements