I was going through the solutions to this problem found on leetcode.
The problem states:
Given an array,
strs, with strings consisting of only 0s and 1s. Also two integersmandn.Now your task is to find the maximum number of strings that you can form with given
m0s andn1s. Each 0 and 1 can be used at most once.
Input:
strs = ["10","0001","111001","1","0"],m = 5,n = 3Output:
4
Explanation: This are totally 4 strings can be formed by the using of 5 0s and 3 1s, which are "10","0001","1","0".
The algorithm used to solve the problem is below:
def findMaxForm(strs, m, n):
dp = [[0] * (n + 1) for _ in range(m +1)]
for s in strs:
zeros, ones = s.count('0'), s.count('1')
for i in range(m, zeros - 1, -1):
for j in range(n, ones -1, - 1):
# dp[i][j] indicates it has i zeros ans j ones,
# can this string be formed with those ?
dp[i][j] = max( 1 + dp[i - zeros][j - ones], dp[i][j])
# print(dp)
return dp[-1][-1]
the confusing part of the problem is the dp[i][j] = max( 1 + dp[i - zeros][j - ones], dp[i][j]). I am not sure what is going on here. Why do we minus i from zeros and j from ones?
I also found a diagram that explains how the dp table should look for ever element in the array.
My Questions:
- what does the first table represent? The x and y axis? Why are there so many
1's. I think if i understand this part, something might click. I would appreciate if someone walks through the diagram - why does this way give us the maximum number of
0's and1's that can be formed? i think i am stil confused about this partdp[i][j] = max( 1 + dp[i - zeros][j - ones], dp[i][j]). - Also the solution is described as a "3d-DP optimized to 2D space: dp[j][k]: i dimension is optimized to be used in-place." What does that mean?
