SDE & MLE Prep

474. Ones and Zeroes

Problem

strs are binary strings. Return the size of the largest subset of them that contains, in total, at most m zeros and at most n ones.

Example: strs = ["10","0001","111001","1","0"], m = 5, n = 3 → 4

Constraints: up to 600 strings; m, n ≤ 100.

0/1 knapsack with two capacities (zeros ≤ m, ones ≤ n). For each string, iterate both capacities downward: dp[i][j] = max(dp[i][j], dp[i−z][j−o] + 1).

Complexity: O(L · 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:
            z, o = s.count("0"), s.count("1")
            for i in range(m, z - 1, -1):
                for j in range(n, o - 1, -1):
                    dp[i][j] = max(dp[i][j], dp[i - z][j - o] + 1)
        return dp[m][n]