
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
Count Colors to Paint Elements in Valid Way Using C++
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
Advertisements