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

📅  最后修改于: 2021-06-25 14:04:29             🧑  作者: 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)