Space
Open
From Fieldwork
Scales
Archive
We use a 2D Dynamic Programming table dp[i][j], where the value represents the maximum number of strings we can form with at most i zeros and j ones. We iterate through the strings and update the table backwards to avoid using the same string multiple times (standard space-optimized Knapsack technique).
class Solution:
def findMaxForm(self, strs: list[str], m: int, n: int) -> int:
# dp[i][j] represents the max subset size with i zeros and j ones
# Dimensions are (m+1) x (n+1) initialized to 0
dp = [[0] * (n + 1) for _ in range(m + 1)]
for s in strs:
# Count costs for the current string
zeros = s.count('0')
ones = len(s) - zeros
# Iterate backwards through the DP matrix to ensure
# we only use the current string once per state.
# We stop when i < zeros or j < ones because the string
# cannot fit in the remaining capacity.
for i in range(m, zeros - 1, -1):
for j in range(n, ones - 1, -1):
dp[i][j] = max(dp[i][j], 1 + dp[i - zeros][j - ones])
return dp[m][n]Practice bench
A private scratchpad for this reading. Nothing is sent or scored.
What is still unclear, or what would change the explanation?
Saved on this device · one draft per mode