A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions.

Given two integers **N** and **M**, where **N** denotes the count of **‘0’ * and *M *denotes the count of *‘1’**, and an integer

- 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:**

_ N = 4, M = 4, K = 2_Input:

_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

_ N = 101, M = 231, K = 15_Input:

_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++

Java

`// C++ Program to implement`

`// the above approach`

`#include <bits/stdc++.h>`

`**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;`

`}`

**Output:**

`320`

**_Time Complexity: _***O(1)***_Auxiliary Space: _***O(1)*- Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the
**DSA Self Paced Course**at a student-friendly price and become industry ready.

combinatorial greedy mathematical strings binary-string permutation and combination

A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions.