Maximum number of objects that can be created as per given conditions
Last Updated :
17 Mar, 2021
Given N items of type-1 and M items of type-2. An object can be created from 2 items of type-1 and 1 item of type-2 or 2 items of type-2 and 1 item of type-1 pieces. The task is to find the maximum number of objects that can be created from given number of items of each type.
Examples:
Input: N = 8, M = 7
Output: 5
Explanation:
3 pairs of 2 type-1 and 1 type-2 objects.
2 pairs of 1 type-1 and 2 type-2 objects.
Input: N = 20, M = 3
Output: 3
Explanation:
3 pairs of 2 type-1 and 1 type-2 objects.
Approach:
Follow the steps below to solve the problem:
- Create two variables initial and final.
- initial = Minimum of N, M.
- final = Divide N + M by 3 ( as an object is made up of 3 components).
- Minimum of initial and final is maximum number of objects that can be created from given N type-1 and M type-2 items.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int numberOfObjects( int N, int M)
{
int initial = min(N, M);
int final = (N + M) / 3;
return min(initial, final);
}
int main()
{
int N = 8;
int M = 7;
cout << numberOfObjects(N, M)
<< endl;
return 0;
}
|
Java
class GFG{
static int numberOfObjects( int N, int M)
{
int initial = Math.min(N, M);
int last = (N + M) / 3 ;
return Math.min(initial, last);
}
public static void main(String[] args)
{
int N = 8 ;
int M = 7 ;
System.out.println(numberOfObjects(N, M));
}
}
|
Python3
def numberOfObjects(N, M):
initial = min (N, M)
final = (N + M) / / 3
return min (initial, final)
if __name__ = = '__main__' :
N = 8
M = 7
print (numberOfObjects(N, M))
|
C#
using System;
class GFG{
static int numberOfObjects( int N, int M)
{
int initial = Math.Min(N, M);
int last = (N + M) / 3;
return Math.Min(initial, last);
}
public static void Main( string [] args)
{
int N = 8;
int M = 7;
Console.Write(numberOfObjects(N, M));
}
}
|
Javascript
<script>
function numberOfObjects(N, M)
{
let initial = Math.min(N, M);
let final = Math.floor((N + M) / 3);
return Math.min(initial, final);
}
let N = 8;
let M = 7;
document.write(numberOfObjects(N, M)
+ "<br>" );
</script>
|
Time Complexity: O(1)
Auxiliary Space Complexity: O(1)
Share your thoughts in the comments
Please Login to comment...