# Ones and Zeroes in C++

Suppose we have a dominator of m 0s and n 1s respectively. On the other hand, there is an array with binary strings. Now our task is to find the maximum number of strings that we can generate with given m 0s and n 1s. Each 0 and 1 can be used at most once. So if the input is like Array = [“10”, “0001”, “111001”, “1”, “0”,] and m = 5 and n = 3, then the output will be 4. This is because there are totally 4 strings can be formed by the using of 5 0s and 3 1s, which are “10,”0001”,”1”,”0”.

To solve this, we will follow these steps −

• Make a matrix of size (m + 1) x (n + 1)
• ret := 0
• for i in range 0 to size of strs array
• one := 0, zero := 0
• for j in range 0 to size of strs[i]
• increase one when star[i, j] is 1, or increase zero when it is 0
• for j in range m down to 0
• for j in range n down to one
• dp[j,k] := max of dp[j,k] and 1 + dp[j – zero, k - one]
• ret := max of ret and dp[j,k]
• return ret

Let us see the following implementation to get better understanding −

## Example

Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int findMaxForm(vector<string>& strs, int m, int n) {
vector < vector <int> > dp(m + 1, vector <int>(n + 1));
int ret = 0;
for(int i = 0; i < strs.size(); i++){
int one = 0;
int zero = 0;
for(int j = 0; j < strs[i].size(); j++){
one += strs[i][j] == '1';
zero += strs[i][j] == '0';
}
for(int j = m; j>= zero; j--){
for(int k = n; k >= one; k--){
dp[j][k] = max(dp[j][k], 1 + dp[j - zero][k - one]);
ret = max(ret, dp[j][k]);
}
}
}
return ret;
}
};
main(){
vector<string> v = {"10","0001","111001","1","0"};
Solution ob;
cout << (ob.findMaxForm(v, 5, 3));
}

## Input

["10","0001","111001","1","0"]
5
3

## Output

4

Advertisements