Data Structures & AlgorithmsHardAmazon · Microsoft OA

Problem: Choose the largest number of binary strings using at most m zeros and n ones in total (2-D 0/1 knapsack).

Problem: Choose the largest number of binary strings using at most m zeros and n ones in total (2-D 0/1 knapsack).
def most(strs, m, n):
    dp = [[0] * (n + 1) for _ in range(m + 1)]
    for s in strs:
        z, o = s.count('0'), s.count('1')
        for i in range(m, z - 1, -1):
            for j in range(n, o - 1, -1):
                dp[i][j] = max(dp[i][j], dp[i-z][j-o] + 1)
    return dp[m][n]
print(most(["10", "0011", "1", "000", "110", "0"], 4, 3))
What is printed?
  1. A. 4
  2. B. 5
  3. C. 2
  4. D. 3

Correct answer: D. 3

Iterating the budgets backwards makes each string usable once. The best is 3 strings, e.g. '10', '1', '0' (2 zeros, 2 ones). A fourth string never fits: '000' pushes zeros to 5, '110' pushes ones to 4, '0011' pushes ones to 4. Greedily taking the shortest strings first is not safe in general; the DP checks all budgets.

More Coding Interview Problems questions

Exams that ask this topic