Program to count maximum number of strings we can generate from list of words and letter counts in python

Suppose we have a list of strings where each string contains two letters "A"s and "B"s. We have two values a and b. We have to find the maximum number of strings that can be formed. We can use at most a number of "A"s and at most b number of "B"s, without reuse.

So, if the input is like strings = ["AAABB", "AABB", "AA", "BB"] a = 4 b = 2, then the output will be 2, as we can take the strings using 4 "A"s and 2 "B"s ["AABB","AA"].

To solve this, we will follow these steps −

  • pairs := a new list
  • for each w in strings, do
    • A := number of "A" in w
    • B := size of w - A
    • insert a pair (A, B) at the end of pairs
  • ans := a map where (a, b) has value 0
  • for each pait (A, B) in pairs, do
    • temp := a new map from ans
    • for each pair (temp_a, temp_b), and value wc of ans, do
      • if temp_a >= A and temp_b >= B, then
        • rem := a pait (temp_a - A, temp_b - B)
        • temp[rem] := maximum of temp[rem] (if rem is not there, 0) and (wc + 1)
      • ans := temp
  • return maximum of list of all values of ans

Let us see the following implementation to get better understanding −


Live Demo

class Solution:
   def solve(self, strings, a, b):
      pairs = []
      for w in strings:
         A = w.count("A")
         B = len(w) - A
         pairs.append((A, B))
      ans = {(a, b): 0}
      for A, B in pairs:
         temp = dict(ans)
         for (temp_a, temp_b), wc in ans.items():
            if temp_a >= A and temp_b >= B:
               rem = (temp_a - A, temp_b - B)
               temp[rem] = max(temp.get(rem, 0), wc + 1)
         ans = temp
      return max(ans.values())

ob = Solution()
strings = ["AAABB", "AABB", "AA", "BB"]
a = 4
b = 2
print(ob.solve(strings, a, b))


["AAABB", "AABB", "AA", "BB"], 4, 2