Ones and Zeroes — 2D 0/1 Knapsack
Advertisement
Problem
Find largest subset of strings using at most m zeros and n ones total.
Approach — 2D 0/1 Knapsack
dp[i][j] = max strings using i zeros and j ones. For each string, update backwards (0/1 property).
Time: O(len * m * n) | Space: O(m*n)
Solutions
Python
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=s.count('1')
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]
C++
class Solution {
public:
int findMaxForm(vector<string>& strs, int m, int n){
vector<vector<int>> dp(m+1,vector<int>(n+1,0));
for(auto& s:strs){
int z=count(s.begin(),s.end(),'0'), o=s.size()-z;
for(int i=m;i>=z;i--) for(int j=n;j>=o;j--)
dp[i][j]=max(dp[i][j],dp[i-z][j-o]+1);
}
return dp[m][n];
}
};
Complexity
- Time: O(|strs| * m * n) | Space: O(m*n)
Advertisement
← Previous
Minimum Falling Path Sum — Grid DP