You are given an array of binary strings strs and two integers m and n.
Return the size of the largest subset of strs such that there are at most m 0s and n 1s in the subset.
Example 1:
Input: strs = ["10","0001","111001","1","0"], m = 5, n = 3
Output: 4
Explanation: The largest subset with at most 5 0's and 3 1's is {"10", "0001", "1", "0"}, so the answer is 4.
Example 2:
Input: strs = ["10","0","1"], m = 1, n = 1
Output: 2
Explanation: The largest subset is {"0", "1"}, so the answer is 2.
strs is empty or if m and n are zero?m and n guaranteed to be non-negative?This problem can be approached using a dynamic programming (DP) solution, where we maintain a 2D DP array dp[i][j]. Here, dp[i][j] represents the maximum number of strings that we can pick with at most i 0s and j 1s.
dp table with dimensions (m+1) x (n+1) to 0.strs, count the number of 0s and 1s.dp[m][n].k be the number of strings in strs.0s and 1s in O(len) where len is the length of the string.(m+1) x (n+1).Thus, the overall time complexity is O(k * len + k * m * n), which simplifies to O(k * len + k * m * n).
Here is the C++ implementation:
#include <vector>
#include <string>
#include <algorithm>
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, 0));
for (const string &s : strs) {
int zeros = count(s.begin(), s.end(), '0');
int ones = count(s.begin(), s.end(), '1');
for (int i = m; i >= zeros; --i) {
for (int j = n; j >= ones; --j) {
dp[i][j] = max(dp[i][j], dp[i - zeros][j - ones] + 1);
}
}
}
return dp[m][n];
}
};
dp[i][j] represents the maximum number of strings we can pick with at most i zeros and j ones.zeros) and ones (ones).dp[m][n]. This is the answer to the problem.By following this approach, we efficiently determine the largest subset of strings that meet the given constraints.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?