
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
Maximum Number of Groups of Size 3 in C++
Given the task is to calculate the maximum number of groups of size 3 that can be formed when N number of items of type A and M number of items of type B are given.
Also, each group should have at least one item of each type, that is either A or B.
Let’s now understand what we have to do using an example −
Input − N=3, M=5
Input − 2
Explanation
Group 1: 1 item of type A and 2 items of type B Group 2: 1 item of type A and 2 items of type B In total, 2 items of type A and 4 items of type B are used.
Input − N=5, M=9
Input − 4
Approach used in the below program as follows
-
The following situation can be divided into 4 cases −
-
Case 1 −
When M>=2N, then maximum number of groups possible = M
-
Case 2 −
When N>=2M, then maximum number of groups possible = N
-
Case 3 −
When (M+N) % 3 == 0, then maximum number of groups possible = (M+N)/3
-
Case 4 −
When none of the above conditions are true then the maximum number of cases become (M+N)/3 + (Any remaining group).
To check if there is any group remaining, set N=N%3 and M=M%3 to obtain the remaining items of both types and then check using the following condition −
If ( N!=0 && M!=0 && (N+M)>=3)
If the above condition is true, then add 1 to the final result.
-
In function MaxGrp(), using if condition check for the above cases
If( M>=2*N ) is true then return M as the answer. Else If( N>=2*M ) is true then return N as the answer.
If both of the above conditions are not true, then check if( (M + N)%3 == 0 ). If it is true then return (M + N)/3 as the answer.
-
If none of the above condition is true then initialize a variable count = (M + N)/3 of type int.
Put N=N%3 and M=M%3 and check for any remaining group using the above stated condition in Case 4. If the condition is true then add 1 to count and return the answer.
Example
#include<bits/stdc++.h> using namespace std; // Implements above mentioned steps. int MaxGrp(int N, int M){ if (N >= 2 * M) return N; if (M >= 2 * N) return M; if ((M + N) % 3 == 0) return (M + N)/3; int count = (M + N)/3; M %= 3; N %= 3; if (M && N && (M + N) >= 3) count++; return count; } int main(){ int N = 5, M = 9; cout << MaxGrp(N, M); return 0; }
Output
If we run the above code we will get the following output −
4