Skip to problem
←

Ones and Zeroes

Medium 0 attempts

Given an array of binary strings strs and two budgets, m zeros and n ones, choose the largest possible number of strings whose combined counts use at most m zeros and at most n ones.

Each array entry can be selected at most once. Equal strings at different indices are separate choices. Select whole strings: you cannot split or edit them. You do not need to use either budget exactly, and selecting no strings is allowed.

Return the maximum number of strings, not their total length or the strings themselves.

For strs = ["10", "0001", "111001", "1", "0"], m = 5, and n = 3, selecting "10", "0001", "1", and "0" uses five zeros and three ones. The answer is 4.

Function contract

Implement findMaxForm(strs, m, n).

Output: Return the maximum number of array entries that fit within both character budgets.

Example 1

Input
strs = ["10","0001","111001","1","0"]
m = 5
n = 3
Output
4

Example 2

Input
strs = ["0","0","1"]
m = 1
n = 1
Output
2
Constraints
  • 1 <= strs.length <= 600
  • 1 <= strs[i].length <= 100
  • 1 <= m, n <= 100
  • Each strs[i] contains only '0' and '1'.

2D Knapsack DP

Let dp[i][j] be the largest number of processed strings that fit within i zeros and j ones. Initially every value is zero, representing the empty selection.

For a string containing zeros zeros and ones ones, either skip it or add it to a selection using the remaining budgets: dp[i - zeros][j - ones] + 1.

Visit both budgets in descending order. This keeps the source state from including the current entry, so one string cannot be selected repeatedly. Descending order also handles strings containing only zeros or only ones. Duplicate entries are processed separately and may each be chosen.

javascript
function findMaxForm(strs, m, n) {
  const dp = Array.from({ length: m + 1 }, () => Array(n + 1).fill(0));
  for (const s of strs) {
    let zeros = 0;
    for (const char of s) if (char === "0") zeros++;
    const ones = s.length - zeros;
    for (let i = m; i >= zeros; i--)
      for (let j = n; j >= ones; j--)
        dp[i][j] = Math.max(dp[i][j], dp[i - zeros][j - ones] + 1);
  }
  return dp[m][n];
}

Time: O(C + S × m × n), where C is total input characters and S is the number of strings | Space: O(m × n)

Loading discussion…

Saved in this browser only. Private to you.

JavaScript