Count of Binary Strings possible as per given conditions
Given two integers N and M, where N denotes the count of ‘0’ and M denotes the count of ‘1’, and an integer K, the task is to find the maximum number of binary strings that can be generated of the following two types:
- A string can consist of K ‘0‘s and a single ‘1‘.
- A string can consist of K ‘1‘s and a single ‘0‘.
Examples:
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
Approach:
Follow the steps below to solve the problem:
- Consider the following three conditions to generate maximum possible combinations of binary strings:
- Number of combinations cannot exceed N.
- Number of combinations cannot exceed M.
- Number of combinations cannot exceed (A+B)/(K + 1).
- Therefore, the maximum possible combinations are min(A, B, (A + B)/ (K + 1)).
- Therefore, the maximum possible strings that can be generated are (K + 1) * min(A, B, (A + B)/ (K + 1)).
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
long long countStrings( long long A,
long long B,
long long K)
{
long long X = (A + B) / (K + 1);
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
import java.io.*;
import java.util.*;
class GFG{
static long countStrings( long A, long B,
long K)
{
long X = (A + B) / (K + 1 );
return (Math.min(A, Math.min(B, X)) *
(K + 1 ));
}
public static void main (String[] args)
{
long N = 101 , M = 231 , K = 15 ;
System.out.print(countStrings(N, M, K));
}
}
|
Python3
def countStrings(A, B, K):
X = (A + B) / / (K + 1 )
return ( min (A, min (B, X)) * (K + 1 ))
N, M, K = 101 , 231 , 15
print (countStrings(N, M, K))
|
C#
using System;
class GFG{
static long countStrings( long A, long B,
long K)
{
long X = (A + B) / (K + 1);
return (Math.Min(A, Math.Min(B, X)) *
(K + 1));
}
public static void Main ( string [] args)
{
long N = 101, M = 231, K = 15;
Console.Write(countStrings(N, M, K));
}
}
|
Javascript
<script>
function countStrings(A, B, K)
{
let X = Math.floor((A + B) / (K + 1));
return (Math.min(A, Math.min(B, X)) * (K + 1));
}
let N = 101, M = 231, K = 15;
document.write(countStrings(N, M, K));
</script>
|
Output:
320
Time Complexity: O(1)
Auxiliary Space: O(1)
Last Updated :
17 Mar, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...