📌  相关文章
📜  根据给定条件可能的二进制字符串计数

📅  最后修改于: 2021-10-26 06:27:57             🧑  作者: Mango

给定两个整数NM ,其中N表示‘0’的计数, M表示‘1’的计数,以及一个整数K ,任务是找到以下两个可以生成的二进制字符串的最大数量类型:

  • 一个字符串可以由K 个0 ”和一个“ 1 ”组成。
  • 一个字符串可以由K 个1 ”和一个“ 0 ”组成。

例子:

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

  • 考虑以下三个条件来生成二进制字符串的最大可能组合:
    • 组合数不能超过N
    • 组合数不能超过M
    • 组合数不能超过(A+B)/(K + 1)
  • 因此,最大可能的组合是min(A, B, (A + B)/ (K + 1))
  • 因此,可以生成的最大可能字符串为(K + 1) * min(A, B, (A + B)/ (K + 1))

下面是上述方法的实现:

C++
// C++ Program to implement
// the above approach
#include 
using namespace std;
 
// Function to generate maximum
// possible strings that can be generated
long long countStrings(long long A,
                    long long B,
                    long long K)
{
 
    long long X = (A + B) / (K + 1);
 
    // Maximum possible strings
    return (min(A, min(B, X)) * (K + 1));
}
int main()
{
 
    long long N = 101, M = 231, K = 15;
    cout << countStrings(N, M, K);
    return 0;
}


Java
// Java program to implement
// the above approach
import java.io.*;
import java.util.*;
 
class GFG{
 
// Function to generate maximum
// possible strings that can be generated
static long countStrings(long A, long B,
                        long K)
{
    long X = (A + B) / (K + 1);
 
    // Maximum possible strings
    return (Math.min(A, Math.min(B, X)) *
                                (K + 1));
}
 
// Driver Code
public static void main (String[] args)
{
    long N = 101, M = 231, K = 15;
     
    System.out.print(countStrings(N, M, K));
}
}
 
// This code is contributed by offbeat


Python3
# Python3 program to implement 
# the above approach 
  
# Function to generate maximum 
# possible strings that can be
# generated 
def countStrings(A, B, K): 
   
    X = (A + B) // (K + 1) 
   
    # Maximum possible strings 
    return (min(A, min(B, X)) * (K + 1)) 
 
# Driver code
N, M, K = 101, 231, 15
 
print(countStrings(N, M, K))
 
# This code is contributed divyeshrabadiya07


C#
// C# program to implement
// the above approach
using System;
 
class GFG{
 
// Function to generate maximum
// possible strings that can be generated
static long countStrings(long A, long B,
                        long K)
{
    long X = (A + B) / (K + 1);
 
    // Maximum possible strings
    return (Math.Min(A, Math.Min(B, X)) *
                                (K + 1));
}
 
// Driver Code
public static void Main (string[] args)
{
    long N = 101, M = 231, K = 15;
     
    Console.Write(countStrings(N, M, K));
}
}
 
// This code is contributed by rock_cool


Javascript


输出:

320

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

如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程学生竞争性编程现场课程