474. Ones and Zeroes #2407
-
|
Topics: You are given an array of binary strings Return the size of the largest subset of A set Example 1:
Example 2:
Constraints:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
|
We need to find the largest subset of binary strings where the total count of 0's is ≤ m and total count of 1's is ≤ n. This is essentially a 2D knapsack problem where each string has a "weight" in terms of zeros and ones, and I need to maximize the number of items (strings) I can select without exceeding capacity m for zeros and n for ones. ApproachI'll use dynamic programming with a 2D DP array:
Let's implement this solution in PHP: 474. Ones and Zeroes <?php
/**
* @param String[] $strs
* @param Integer $m
* @param Integer $n
* @return Integer
*/
function findMaxForm($strs, $m, $n) {
// Initialize DP table
$dp = array_fill(0, $m + 1, array_fill(0, $n + 1, 0));
foreach ($strs as $str) {
// Count zeros and ones in current string
$zeros = substr_count($str, '0');
$ones = strlen($str) - $zeros;
// Update DP table from bottom-right to avoid reusing same string
for ($i = $m; $i >= $zeros; $i--) {
for ($j = $n; $j >= $ones; $j--) {
$dp[$i][$j] = max($dp[$i][$j], $dp[$i - $zeros][$j - $ones] + 1);
}
}
}
return $dp[$m][$n];
}
// Test cases
// ---------- Example 1 ----------
$strs = ["10","0001","111001","1","0"];
$m = 5;
$n = 3;
echo findMaxForm($strs, $m, $n); // Output: 4
// ---------- Example 2 ----------
$strs = ["10","0","1"];
$m = 1;
$n = 1;
echo "\n" . findMaxForm($strs, $m, $n); // Output: 2
?>Explanation:
Complexity Analysis
Example WalkthroughFor
The optimal subset is {"10", "0001", "1", "0"} with total zeros=5 and ones=3, giving answer 4. The DP approach efficiently explores all combinations while respecting both capacity constraints. |
Beta Was this translation helpful? Give feedback.
We need to find the largest subset of binary strings where the total count of 0's is ≤ m and total count of 1's is ≤ n.
This is essentially a 2D knapsack problem where each string has a "weight" in terms of zeros and ones, and I need to maximize the number of items (strings) I can select without exceeding capacity m for zeros and n for ones.
Approach
I'll use dynamic programming with a 2D DP array:
dp[i][j]= maximum number of strings that can be selected with at most i zeros and j onesLet's implement this solution in PHP: 474. Ones and Zeroes