给定两个整数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)