Ones and Zeroes
Difficulty: Medium · Pattern: 2-D Dynamic Programming · LeetCode #474
Given binary strings strs and integers m and n, return the size of the largest subset of strs that contains at most m zeros and n ones in total.
Examples
text
strs = ["10","0001","111001","1","0"], m = 5, n = 3 → 4 ({"10","0001","1","0"})
strs = ["10","0","1"], m = 1, n = 1 → 2Hints
- Each string is an item with two "weights" (its zeros and its ones) and value 1.
- That's a 0/1 knapsack with a 2-D capacity:
dp[i][j]= the max number of strings using at most i zeros and j ones.
Approach
text
dp = (m+1) × (n+1) zeros
for s in strs:
z, o = s.count('0'), s.count('1')
for i from m down to z:
for j from n down to o:
dp[i][j] = max(dp[i][j], dp[i-z][j-o] + 1)Iterating both capacities downward is what prevents a string from being used twice. It's the 0/1-knapsack rule, applied in two dimensions. O(L · m · n).
Complexity
Time: O(L · m · n). Space: O(m · n).
Python solution
def findMaxForm(strs, m, n):
dp = [[0] * (n + 1) for _ in range(m + 1)]
for s in strs:
z = s.count('0')
o = len(s) - z
for i in range(m, z - 1, -1):
for j in range(n, o - 1, -1):
if dp[i - z][j - o] + 1 > dp[i][j]:
dp[i][j] = dp[i - z][j - o] + 1
return dp[m][n]JavaScript solution
function findMaxForm(strs, m, n) {
const dp = Array.from({ length: m + 1 }, () => new Array(n + 1).fill(0));
for (const s of strs) {
let z = 0;
for (const ch of s) if (ch === '0') z++;
const o = s.length - z;
for (let i = m; i >= z; i--) for (let j = n; j >= o; j--) dp[i][j] = Math.max(dp[i][j], dp[i - z][j - o] + 1);
}
return dp[m][n];
}