Ones and Zeroes

Medium · Dynamic Programming · Array · String · Dynamic Programming

Problem

You are given an array strs of binary strings and two integers m and n.

Choose a subset of the strings such that, across all chosen strings together, there are at most m zeros and at most n ones. Return the largest possible size of such a subset.

Examples

Input: strs = ["01","110","0","1000","11"], m = 3, n = 2
Output: 2

For example {"01", "0"} or {"0", "11"} fits; no three strings stay within 3 zeros and 2 ones.

Input: strs = ["1","1","0","00"], m = 1, n = 2
Output: 3

Take "1", "1" and "0": exactly 1 zero and 2 ones.

Input: strs = ["000","111"], m = 2, n = 2
Output: 0

Each string alone needs three of one digit, so the best subset is empty.

Constraints

Approaches

Follow-up

Every extra resource adds one dimension to the knapsack table. The use cases give each string a value (maximize total value instead of count) and ask how many subsets fit, which swaps max for a sum.

Related problems

Start free on Cariara · Coding problems · System design studio

Starting Python
No results yet.

          
↑↓ move ↵ open esc close

Labs

Loading labs…

Run with your own input

Starting Python

Loading Python…