You are given an array of binary strings strs
and two integers m
and n
.
strs[i]
represents a binary string consisting only of ‘0’s and ‘1’s.m
represents the maximum number of ‘0’s you can have.n
represents the maximum number of ‘1’s you can have.Your task is to find the maximum number of strings you can form from the given array strs
without exceeding the given values of m
and n
.
strs
is empty?
strs
or values of m
and n
?
1 <= strs.length <= 600
1 <= strs[i].length <= 100
strs[i]
consists only of ‘0’s and ‘1’s.0 <= m, n <= 100
.This problem requires a dynamic programming (DP) approach because it involves making decisions at each step to maximize the outcome while keeping track of resource constraints (m
and n
). We can use a 2D DP array where dp[i][j]
represents the maximum number of strings that can be formed with at most i
‘0’s and j
‘1’s.
(m+1) x (n+1)
initialized to 0.strs
, count the number of ‘0’s and ‘1’s.def findMaxForm(strs, m, n):
# Initialize the DP table
dp = [[0] * (n + 1) for _ in range(m + 1)]
# Process each string in strs
for s in strs:
zeros = s.count('0')
ones = s.count('1')
# Update the DP table backwards
for i in range(m, zeros - 1, -1):
for j in range(n, ones - 1, -1):
dp[i][j] = max(dp[i][j], dp[i - zeros][j - ones] + 1)
return dp[m][n]
# Example Usage
strs = ["10", "0001", "111001", "1", "0"]
m = 5
n = 3
print(findMaxForm(strs, m, n)) # Output will be 4
Total Time Complexity: O(S * L + S * m * n), where S is the number of strings and L is the maximum length of a string in strs
.
This ensures the solution is efficient given the 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?