给定两个整数N和M ,其中N表示‘0’的计数, M表示‘1’的计数,以及一个整数K ,任务是找到以下两个可以生成的二进制字符串的最大数量类型:
- 一个字符串可以由K 个“ 0 ”和一个“ 1 ”组成。
- 一个字符串可以由K 个“ 1 ”和一个“ 0 ”组成。
例子:
Input: N = 4, M = 4, K = 2
Output: 6
Explanation:
Count of ‘0‘s = 4
Count of ‘1‘s = 4
Possible ways to combine 0’s and 1’s under given constraints are {“001”, “001”} or {“001”, “110”} or {“110”, “110”}
Therefore, at most 2 combinations exists in a selection.
Each combination can be arranged in K + 1 ways, i.e. “001” can be rearranged to form “010, “100” as well.
Therefore, the maximum possible strings that can be generated is 3 * 2 = 6
Input: N = 101, M = 231, K = 15
Output: 320
方法:
请按照以下步骤解决问题:
- 考虑以下三个条件来生成二进制字符串的最大可能组合:
- 组合数不能超过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 现场工作专业课程和学生竞争性编程现场课程。