# C++ code to count maximum groups can be made

C++Server Side ProgrammingProgramming

#### C in Depth: The Complete C Programming Guide for Beginners

45 Lectures 4.5 hours

#### Practical C++: Learn C++ Basics Step by Step

Most Popular

50 Lectures 4.5 hours

#### Master C and Embedded C Programming- Learn as you go

Best Seller

66 Lectures 5.5 hours

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 12:27:18