Maximum number of 3-person teams formed from two groups in C++

C++Server Side ProgrammingProgramming

In this problem, we are given two integers N and M, N is the number of people in group 1, and M is the number of people in group 2. Our task is to create a program to find the maximum number of 3-person teams formed from two groups.

We will be creating teams of 3 people by selecting a person from these groups such that the maximum teams can be made. Each team must have at least one person from each group.

Let’s take an example to understand the problem,

Input − N = 5, M = 3

Output − 2

Explanation

The teams will be as follows −

Team 1: Group 1 Member->2 ; Group 2 Member->1
Left in Group 1 = 3 ; left in Group 2 = 2
Team 2: Group 1 Member->2 ; Group 2 Member->1
Left in Group 1 = 1 ; left in Group 2 = 1
No more teams of 3 can be formed.

To solve this problem, we will create teams taking 1 member form group with fewer persons and 2 members from the other group. And update the count of persons in each group. Also, we will maintain a count of teams and increment it after each team creation until the team creation is possible.

Example

Program to find the maximum number of 3-person teams formed from two groups −

 Live Demo

#include <iostream>
using namespace std;
int CountTeams(int N, int M) {
   int teamCount = 0;
   while (N >= 1 && M >= 1 && N + M >= 3) {
      if (N > M) {
         N = N-2;
         M = M-1;
      }
      else {
         N = N-1;
         M = M-2;
      }
      teamCount++;
   }
   return teamCount;
}
int main() {
   int N = 5, M = 3;
   cout<<"The maximum number of 3-person teams is "<<CountTeams(N, M);
   return 0;
}

Output

The maximum number of 3-person teams is 2
raja
Updated on 03-Jun-2020 08:38:05

Advertisements