- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- 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++ program to find number of groups can be formed from set of programmers
Suppose we have an array A with n elements. The A[i] represents the programming skill of ith student. All elements in A are distinct. We want to split them into teams in such a way that −
No two students i and j, such that |A[i] - A[j]| = 1 belong to the same team
The number of teams is the minimum possible.
So, if the input is like A = [2, 3, 4, 99, 100], then the output will be 2, because the groups are [2, 3, 4] and [99, 100]
Steps
To solve this, we will follow these steps −
dem := 1 sort the array A for initialize i := 1, when i < size of A, update (increase i by 1), do: if A[i] - A[i - 1] is same as 1, then: dem := 2 return dem
Example
Let us see the following implementation to get better understanding −
#include <bits/stdc++.h> using namespace std; int solve(vector<int> A) { int dem = 1; sort(A.begin(), A.end()); for (int i = 1; i < A.size(); i++) if (A[i] - A[i - 1] == 1) dem = 2; return dem; } int main() { vector<int> A = { 2, 3, 4, 99, 100 }; cout << solve(A) << endl; }
Input
{ 2, 3, 4, 99, 100 }
Output
2
Advertisements