Problem 551182 · medium · Phase 05 Advanced Algorithms & Graphs

Codes on a Tiny Chip

dynamic programming · knapsack · two-dimensional capacity

A tiny memory chip can store at most zero_limit zero bits and one_limit one bits in total. You are given binary strings codes; each chosen code uses up its own zeros and ones. Return the largest number of codes that fit on the chip together (each code at most once).

Examples

Input:  codes = ["01", "1", "000", "110", "0"], zero_limit = 3, one_limit = 2
Output: 3
Explanation: "01", "1" and "0" use 2 zeros and 2 ones.

Input:  codes = ["11", "0"], zero_limit = 1, one_limit = 1
Output: 1

Constraints

  • 0 <= len(codes) <= 100
  • 1 <= len(codes[i]) <= 50, each character is '0' or '1'
  • 0 <= zero_limit, one_limit <= 50
  • Target complexity: O(len(codes) * zero_limit * one_limit).

Goals

  • Handle a knapsack with two separate capacity limits
  • Update a 2D table in reverse order so each code is used once
Starting Python…