
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
C++ Code to Count Maximum Groups Can Be Made
Suppose we have an array A with n elements. There were n groups of students. A group is either one person who can write the code with anyone else, or two people who want to write the code in the same team. But the mentor decided to form teams of exactly three people. We have to find the maximum number of teams of three people the mentor can form. For groups of two, either both students should write the code, or both should not. If two students from a group of two will write the code, they should be in the same team.
So, if the input is like A = [2, 2, 2, 1, 1, 1, 1], then the output will be 3, because the mentor can make teams like: [First group of two people and the seventh group of one person], [The second group of two people and the sixth group of one person], [The third group of two people and the fourth group of one person].
Steps
To solve this, we will follow these steps −
p := 0 q := 0 x := size of A for initialize i := 0, when i < x, update (increase i by 1), do: a := A[i] if a is same as 1, then: p := p + 1 Otherwise q := q + 1 if p > q, then: return q + (p - q) otherwise when p < q, then: return p Otherwise return p
Example
Let us see the following implementation to get better understanding −
#include <bits/stdc++.h> using namespace std; int solve(vector<int> A){ int p = 0, q = 0; int x = A.size(); for (int i = 0; i < x; i++){ int a = A[i]; if (a == 1){ p = p + 1; } else{ q = q + 1; } } if (p > q){ return q + (p - q) / 3; } else if (p < q){ return p; } else{ return p; } } int main(){ vector<int> A = { 2, 2, 2, 1, 1, 1, 1 }; cout << solve(A) << endl; }
Input
{ 2, 2, 2, 1, 1, 1, 1 }
Output
3