📜  使用 M 0 和 N 1 可以形成的 001 和 110 的数量最大化

📅  最后修改于: 2022-05-13 01:56:04.771000             🧑  作者: Mango

使用 M 0 和 N 1 可以形成的 001 和 110 的数量最大化

给定两个整数N (表示“1”的数量)和M (表示“0”的数量)。任务是最大化使用给定数量的字符可以形成的“001”“110”模式的数量。

例子:

方法:这个问题可以通过将整个问题分解为案例来解决。请按照以下步骤解决给定的问题。

  • 如果N/2 >= M则只会形成001个模式,在这种情况下,最大模式数将为M
  • 如果M/2 >= N则只会形成110个模式,在这种情况下,最大模式数将为N
  • 否则,如果abs(NM) < 2*min(N, M)在这种情况下(N+M)/3将被输出。
  • 根据以上条件打印结果。

下面是上述方法的实现:

C++
// C++ code to implement above approach
#include 
using namespace std;
 
// Function to find the maximum
// possible patterns that can be formed
int geeksforgeeks(int N, int M)
{
    // To store the number of patterns
    // formed by using 0 and 1
    int ans = 0;
    if ((N / 2) >= M) {
        ans = M;
    }
    else if ((M / 2) >= N) {
        ans = N;
    }
    else {
        ans = (N + M) / 3;
    }
    return ans;
}
 
// Driver Code
int main()
{
    int N, M;
    N = 7;
    M = 10;
 
    // Function call
    cout << geeksforgeeks(N, M);
    return 0;
}


Java
// Java program for the above approach
class GFG {
 
    // Function to find the maximum
    // possible patterns that can be formed
    static int geeksforgeeks(int N, int M) {
 
        // To store the number of patterns
        // formed by using 0 and 1
        int ans = 0;
        if ((N / 2) >= M) {
            ans = M;
        } else if ((M / 2) >= N) {
            ans = N;
        } else {
            ans = (N + M) / 3;
        }
        return ans;
    }
 
    // Driver Code
    public static void main(String args[]) {
        int N, M;
        N = 7;
        M = 10;
 
        // Function call
        System.out.println(geeksforgeeks(N, M));
    }
}
 
// This code is contributed by gfgking


Python3
# Python 3 code to implement above approach
 
# Function to find the maximum
# possible patterns that can be formed
def geeksforgeeks(N,  M):
 
    # To store the number of patterns
    # formed by using 0 and 1
    ans = 0
    if ((N // 2) >= M):
        ans = M
 
    elif ((M // 2) >= N):
        ans = N
 
    else:
        ans = (N + M) // 3
 
    return ans
 
# Driver Code
if __name__ == "__main__":
 
    N = 7
    M = 10
 
    # Function call
    print(geeksforgeeks(N, M))
 
    # This code is contributed by ukasp.


C#
// C# program for the above approach
using System;
class GFG
{
 
  // Function to find the maximum
  // possible patterns that can be formed
  static int geeksforgeeks(int N, int M)
  {
 
    // To store the number of patterns
    // formed by using 0 and 1
    int ans = 0;
    if ((N / 2) >= M) {
      ans = M;
    }
    else if ((M / 2) >= N) {
      ans = N;
    }
    else {
      ans = (N + M) / 3;
    }
    return ans;
  }
 
  // Driver Code
  public static void Main()
  {
    int N, M;
    N = 7;
    M = 10;
     
    // Function call
    Console.Write(geeksforgeeks(N, M));
 
  }
}
 
// This code is contributed by Samim Hossain Mondal.


Javascript


输出
5

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