📌  相关文章
📜  根据给定条件可以创建的最大对象数

📅  最后修改于: 2021-04-24 16:58:25             🧑  作者: Mango

给定N个类型1项和M个类型2项。对象可以从2项1型和2型的1项2项类型2和类型-11个项目被创建。任务是从每种类型的给定数量的项目中找到可以创建的最大对象数。
例子:

方法:
请按照以下步骤解决问题:

  • 创建两个变量initialfinal
  • 初始= N,M的最小值
  • final =将N + M除以3(因为对象由3个成分组成)。
  • 初始和最终值的最小值是可以从给定的N个Type-1和M个type-2项目创建的最大对象数。

下面是上述方法的实现:

C++
// C++ program for the above problem
#include 
using namespace std;
 
// Function for finding
// the maximum number of
// objects from N type-1 and
// M type-2 items
 
int numberOfObjects(int N, int M)
{
    // storing minimum of N and M
    int initial = min(N, M);
 
    // storing maximum number of
    // objects from given items
    int final = (N + M) / 3;
 
    return min(initial, final);
}
 
// Driver Code
int main()
{
    int N = 8;
    int M = 7;
    cout << numberOfObjects(N, M)
         << endl;
    return 0;
}


Java
// Java program for the above problem
class GFG{
     
// Function for finding
// the maximum number of
// objects from N type-1 and
// M type-2 items
static int numberOfObjects(int N, int M)
{
     
    // Storing minimum of N and M
    int initial = Math.min(N, M);
 
    // Storing maximum number of
    // objects from given items
    int last = (N + M) / 3;
 
    return Math.min(initial, last);
}
 
// Driver Code
public static void main(String[] args)
{
    int N = 8;
    int M = 7;
     
    System.out.println(numberOfObjects(N, M));
}
}
 
// This code is contributed by rutvik_56


Python3
# Python3 program for the above problem
 
# Function for finding
# the maximum number of
# objects from N type-1 and
# M type-2 items
def numberOfObjects(N, M):
     
    # Storing minimum of N and M
    initial = min(N, M)
 
    # Storing maximum number of
    # objects from given items
    final = (N + M) // 3
 
    return min(initial, final)
 
# Driver Code
if __name__ == '__main__':
     
    N = 8
    M = 7
     
    print(numberOfObjects(N, M))
 
# This code is contributed by mohit kumar 29


C#
// C# program for the above problem
using System;
class GFG{
      
// Function for finding
// the maximum number of
// objects from N type-1 and
// M type-2 items
static int numberOfObjects(int N, int M)
{
      
    // Storing minimum of N and M
    int initial = Math.Min(N, M);
  
    // Storing maximum number of
    // objects from given items
    int last = (N + M) / 3;
  
    return Math.Min(initial, last);
}
  
// Driver Code
public static void Main(string[] args)
{
    int N = 8;
    int M = 7;
      
    Console.Write(numberOfObjects(N, M));
}
}
  
// This code is contributed by rock_cool


Javascript


输出:
5

时间复杂度: O(1)
辅助空间复杂度: O(1)