I treat this as a 0/1 knapsack with two capacity dimensions: number of zeros m and number of ones n. For each string I count how many zeros and ones it needs. I maintain a 2D DP table dp[i][j] = maximum number of strings selectable using at most i zeros and j ones. For each string I update the DP in reverse (from m down to zeros and n down to ones) so each string is used at most once. The answer is dp[m][n].
class Solution:
def findMaxForm(self, strs: List[str], m: int, n: int) -> int:
dp = [[0] * (n + 1) for _ in range(m + 1)]
for s in strs:
zeros = s.count('0')
ones = len(s) - zeros
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]- Time: O(len(strs) * m * n)
- Space: O(m * n)