# 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

Updated on: 30-Mar-2022

332 Views