Suppose we have a list of numbers called counts where counts[i] represents the number of items are of type i. We also have another value k. We have to find the maximum number of groups of size k we can find, such that each group must have items of distinct types.
So, if the input is like counts = [2, 3, 5, 3] k = 2, then the output will be 6, because let four types of items are represented by a, b, c, d respectively. We can have the following groups of k = 2, where all elements are of distinct types: [(c, a), (b, a), (c, b), (c, b), (d, a), (d, a)].
To solve this, we will follow these steps −
Let us see the following implementation to get better understanding −
def possible(counts, groups, k): required = groups * k for i in range(len(counts)): temp = min(counts[i], groups, required) required -= temp if required == 0: return True return False def solve(counts, k): res = 0 l = 0 r = sum(counts) while l <= r: m = l + (r - l) // 2 if possible(counts, m, k): l = m + 1 res = max(res, m) else: r = m - 1 return res counts = [2, 3, 5, 3] k = 2 print(solve(counts, k))
[2, 3, 5, 3], 2